杰克逊序列化Java对象与地图? [英] jackson serialization for Java object with Map?

查看:60
本文介绍了杰克逊序列化Java对象与地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的Java类,并且想使用Jackson转换为JSON.感谢您的帮助.

I have a Java class like this and want to convert to JSON using Jackson. Thanks for your help.

  1. Java类

public class myClass {
   String Id;
   Map<String, Object> optionalData = new LinkedHashMap<String, Object>();
}

  • 如何使用Jackson ObjectMapper将其序列化为JSON?

  • How to serialization it to JSON using Jackson ObjectMapper ?

  • 例如,假设optionalData是保存两个条目<"type", "book"><"year", "2014">的Map 我希望输出如下.请注意,optionalData的键/值可以随时更改(因此,如果不使用Map,则无法为此创建静态" Java对象)

    For example, suppose the optionalData is a Map saving two entries <"type", "book"> and <"year", "2014"> I want the output to be as follow. Please note that the key/value of optionalData could be changed on the fly (so, I cannot create a "static" Java object for this without using Map)

      [ 
        { 
          id: "book-id1",
          type: "book",
          year: "2014"
        },
        { 
          id: "book-id2",
          type: "book",
          year: "2013"
         }
      ]
    

    推荐答案

    您可以在getter方法上使用@JsonAnyGetter批注,该方法将返回可选值的映射.请参阅此博客文章,其中对此进行了详细说明.

    You can use the @JsonAnyGetter annotation on a getter method that returns the map of optional values. Please refer to this blog plost that explains that in details.

    这里是一个例子:

    public class JacksonAnyGetter {
    
        public static class myClass {
            final String Id;
            private final Map<String, Object> optionalData = new LinkedHashMap<>();
    
            public myClass(String id, String key1, Object value1, String key2, Object value2) {
                Id = id;
                optionalData.put(key1, value1);
                optionalData.put(key2, value2);
            }
    
            public String getid() {
                return Id;
            }
    
            @JsonAnyGetter
            public Map<String, Object> getOptionalData() {
                return optionalData;
            }
        }
    
        public static void main(String[] args) throws JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
            List<myClass> objects = Arrays.asList(
                    new myClass("book-id1", "type", "book", "year", 2013),
                    new myClass("book-id2", "type", "book", "year", 2014)
            );
            System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(objects));
        }
    
    }
    

    输出:

    [ {
      "id" : "book-id1",
      "type" : "book",
      "year" : 2013
    }, {
      "id" : "book-id2",
      "type" : "book",
      "year" : 2014
    } ]
    

    这篇关于杰克逊序列化Java对象与地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆