2016-05-09 4 views
0

私はJavaクラスの階層にjsonのシリアル化(ジャクソンを使用)を書いています。つまり、クラスは他のクラスで構成されています。私はすべてのプロパティをシリアル化しているわけではないので、私はJsonViewを使い、シリアル化したいプロパティだけを注釈しました。この階層の最上位にあるクラスには、シリアライズ/デシリアライズも必要なマップが含まれています。シリアライザ/デシリアライザをマップ専用に書くことは可能ですか?デフォルトのシリアライザで残りのオブジェクトをシリアライズする必要がありますハッシュマップのみのためのジャクソンのカスタムJsonデシリアライザ

なぜこの要件が必要ですか?一番上のクラスのシリアライザを定義すると、すべてのオブジェクトに対してシリアライザを実行する必要があります。 JsonGeneratorオブジェクトはJsonViewアノテーションを無視し、すべてのプロパティをシリアライズしているようです。

答えて

1

確かに可能です。 Mapクラスジェネリック型でカスタムシリアライザを定義し、次にJacksonモジュールサブシステムを使用してバインドします。

public class Test 
{ 
    // the "topmost" class 
    public static class DTO { 
     public String name = "name"; 
     public boolean b = false; 
     public int i = 100; 

     @JsonView(MyView.class) 
     public Map<String, String> map; { 
      map = new HashMap<>(); 
      map.put("key1", "value1"); 
      map.put("key2", "value2"); 
      map.put("key3", "value3"); 
     } 
    } 

    // just to prove it works with views... 
    public static class MyView {} 

    // custom serializer for Map 
    public static class MapSerializer extends JsonSerializer<Map> { 
     @Override 
     public void serialize(Map map, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { 
      // your custom serialization goes here .... 
      gen.writeStartObject(); 
      gen.writeFieldName("map-keys"); 
      gen.writeStartArray(); 
      gen.writeString(map.keySet().toString()); 
      gen.writeEndArray(); 
      gen.writeFieldName("map-valuess"); 
      gen.writeStartArray(); 
      gen.writeString(map.values().toString()); 
      gen.writeEndArray(); 
      gen.writeEndObject(); 
     } 
    } 

    public static void main(String[] args) { 
     SimpleModule module = new SimpleModule(); 
     module.addSerializer(Map.class, new MapSerializer()); 
     ObjectMapper mapper = new ObjectMapper(); 
     mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); 
     mapper.registerModule(module); 
     try { 
      mapper.writerWithView(MyView.class).writeValue(System.out, new DTO()); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

(それは愚かなカスタムのシリアル化を生成するが、校長が有効である)そして、あなたは同様に別のカスタムデシリアライザで、「readerWithView」のようなものを使用して、このオブジェクトをデシリアライズすることができます:ここで

は一例ですか? –

関連する問題