简体   繁体   English

如何反序列化JSON HashMap <String, Object> ?

[英]How to deserialize a JSON HashMap<String, Object>?

This is my situation: 这是我的情况:

private Map<String, Object> data = new HashMap<>();

public void setName(String x) {put("name", x);}
public String getName() {return (String)get("name");}

public void setAge(Integer x) {put("age", x);}
public Integer getAge() {return (Integer)get("age");}

public void setUUID(UUID x) {put("uuid", x);}
public UUID getUUID() {return (UUID)get("uuid");}

Now when I generate JSON from this object I get {"data":{"name": ...}} I don't want the "data":{} part. 现在,当我从这个对象生成JSON时,我得到{“data”:{“name”:...}}我不想要“数据”:{}部分。

How to fix this? 如何解决这个问题?

[EDIT] When this class is exported as JSON by Spring the format is exactly what I want. [编辑]当这个类被Spring导出为JSON时,格式正是我想要的。

Since your entire class seems to be inside a map, simply add a getter method for the Map to you class and instead of serializing the class itself, do it like: 由于您的整个类似乎都在地图中,只需将Map的getter方法添加到您的类中,而不是序列化类本身,请执行以下操作:

gson.toJson(foo.getData())

On a side note, I gotta say it is pretty awkward having getters and setters doing actions on a map. 在旁注中,我得说,让getters和setter在地图上做动作是非常尴尬的。

This works for me. 这适合我。

    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(myClass);

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

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