【问题标题】:Custom Json Deserializer in Jackson for Hashmap onlyJackson 中的自定义 Json 反序列化器仅适用于 Hashmap
【发布时间】:2016-09-03 21:12:03
【问题描述】:

我正在为 Java 类的层次结构编写 json 序列化(使用 Jackson),即这些类由其他类组成。因为,我没有序列化所有属性,所以我使用了 JsonViews 并且只注释了我想要序列化的那些属性。此层次结构顶部的类包含一个也需要序列化/反序列化的 Map。是否可以仅为 Map 编写序列化器/反序列化器?我希望默认序列化程序负责序列化其余对象

为什么有这个要求?如果我为最顶层的类定义一个序列化程序,那么我需要对所有对象进行序列化。 JsonGenerator 对象似乎忽略了 JsonView 注释并序列化所有属性。

【问题讨论】:

    标签: java json serialization jackson


    【解决方案1】:

    当然可以。您使用 Map 类泛型类型定义自定义 Serializer,然后使用 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();
            }
        }
    }
    

    【讨论】:

    • 你是否可以使用类似“readerWithView”之类的东西和另一个自定义反序列化器来反序列化这个对象?
    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 2016-01-29
    • 2014-08-02
    • 2013-10-10
    • 2013-01-18
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多