jackson serialization for Java object with Map?
我有这样的Java类,并希望使用杰克逊转换为JSON。谢谢你的帮助。
例如,假设
1 2 3 4 5 6 7 8 9 10 11 12 | [ { id:"book-id1", type:"book", year:"2014" }, { id:"book-id2", type:"book", year:"2013" } ] |
号
您可以在getter方法上使用
下面是一个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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)); } } |
输出:
1 2 3 4 5 6 7 8 9 | [ { "id" :"book-id1", "type" :"book", "year" : 2013 }, { "id" :"book-id2", "type" :"book", "year" : 2014 } ] |
。
您需要编写自己的EDCOX1 OR 0,以根据需要从Java对象创建自定义JSON字符串。
下面是一些不错的帖子和示例
JSON序列化程序和反序列化程序如何在Jackson中使用自定义序列化程序?
如何编写Jackson JSON序列化程序和反序列化程序?
使用EDOCX1[1]也可以实现相同的功能
下面是一些例子
用GSON序列化Java对象
GSON Serialiser示例-JavaCreed
这是使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | List<MyClass> list = new ArrayList<MyClass>(); MyClass myClass1 = new MyClass(); myClass1.setId("book-id1"); myClass1.getOptionalData().put("type","book"); myClass1.getOptionalData().put("year","2014"); list.add(myClass1); MyClass myClass2 = new MyClass(); myClass2.setId("book-id2"); myClass2.getOptionalData().put("type","book"); myClass2.getOptionalData().put("year","2013"); list.add(myClass2); class MyClassSerialiser implements JsonSerializer<MyClass> { @Override public JsonElement serialize(final MyClass obj, final Type typeOfSrc, final JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("id", obj.getId()); Map<String, String> optioanlData = obj.getOptionalData(); if (optioanlData.size() > 0) { for (Map.Entry<String, String> entry : optioanlData.entrySet()) { jsonObject.addProperty(entry.getKey(), entry.getValue()); } } return jsonObject; } } String jsonString = new GsonBuilder().setPrettyPrinting(). .registerTypeAdapter(MyClass.class, new MyClassSerialiser()).create() .toJson(list); System.out.println(jsonString); |
输出:
1 2 3 4 5 6 7 8 9 10 11 12 | [ { "id":"book-id1", "type":"book", "year":"2014" }, { "id":"book-id2", "type":"book", "year":"2013" } ] |
号