简体   繁体   中英

Custom Json Deserializer in Jackson for Hashmap only

I'm writing json serialization (using Jackson) for a hierarchy of Java classes, ie the classes are composed of other classes. Since, I'm not serializing all properties, I've used JsonViews and have annotated only those properties that I want to serialize. The class at the top of this hierarchy contains a Map which also needs to be serialized/deserialized. Is it possible to write a serializer/deserializer only for the Map ? I want the default serializer to take care of serializing the rest of the objects

Why this requirement ? If I define a serializer for the topmost class, then I would need to do the serialization for all the objects. The JsonGenerator object seems to ignore the JsonView annotations and serializes all properties.

Sure its possible. You define your custom Serializer with the Map class generic type, then bind it using Jackson module subsystem.

Here is an example: (it produces silly custom serialization, but the principal is valid)

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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM