简体   繁体   English

如何使用基于java.util.Map的类序列化Jackson

[英]How to serialize with Jackson a java.util.Map based class

I have a class which 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 a 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 executing this code I'm getting the following output: {"str1":"str2"} 执行此代码时,我得到以下输出:{“str1”:“str2”}

My question is why the internal property "myProperty" is not serialized with the map? 我的问题是为什么内部属性“myProperty”没有与地图序列化? What should be done to serialize internal properties? 如何序列化内部属性?

Most probably you will end up with implementing your own serializer which will handle your custom Map type. 最有可能的是,您最终会实现自己的序列化程序,它将处理您的自定义Map类型。 Please refer to this question for more information. 有关更多信息,请参阅此问题

If you choose to replace inheritance with composition, that is to make your class to include a map field not to extend a map, then it is pretty easy to solve this using the @JsonAnyGetter annotation . 如果您选择使用合成替换继承,即使您的类包含不扩展地图的地图字段,那么使用@JsonAnyGetter注释很容易解决这个问题。

Here is an example: 这是一个例子:

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

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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