How to serialize java.util.Map class with Jackson

I have a class that looks like this:

@JsonFormat(shape=JsonFormat.Shape.OBJECT)
public class MyMap implements Map<String, String>
{
    protected Map<String, String> myMap = new HashMap<String, String>();

    protected String myProperty = "my property";
    public String getMyProperty()
    {
        return myProperty;
    }
    public void setMyProperty(String myProperty)
    {
        this.myProperty = myProperty;
    }

    //
    // java.util.Map mathods implementations
    // ...
}

And the main method with this code:

            MyMap map = new MyMap();
            map.put("str1", "str2");

            ObjectMapper mapper = new ObjectMapper();
            mapper.getDeserializationConfig().withAnnotationIntrospector(new JacksonAnnotationIntrospector());
            mapper.getSerializationConfig().withAnnotationIntrospector(new JacksonAnnotationIntrospector());
            System.out.println(mapper.writeValueAsString(map));

When I execute this code, I get the following output: {"str1": "str2"}

My question is why the internal property "myProperty" does not serialize with the map? What needs to be done to serialize internal properties?

+4
source share
1 answer

Most likely, you will be able to implement your own serializer, which will process your own type of card. See this question for more information .

, , , , @JsonAnyGetter.

:

public class JacksonMap {

    public static class Bean {
        private final String field;
        private final Map<String, Object> map;

        public Bean(String field, Map<String, Object> map) {
            this.field = field;
            this.map = map;
        }

        public String getField() {
            return field;
        }

        @JsonAnyGetter
        public Map<String, Object> getMap() {
            return map;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        Bean map = new Bean("value1", Collections.<String, Object>singletonMap("key1", "value2"));
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(map));
    }
}

:

{"field":"value1","key1":"value2"}
+3

Source: https://habr.com/ru/post/1547598/


All Articles