简体   繁体   English

如何使用 Gson 将 json 转换为嵌套地图?

[英]How to convert json to nested Maps using Gson?

I have a POJO MyModel.java :我有一个 POJO MyModel.java

public class MyModel {
  String displayName;
  String id;
  StepDetails stepDetails;
}

In StepDetails.java I have:StepDetails.java我有:

public class StepDetails {
  V1 v1;
  V2 v2;
}

In V1.java and V2.java , both are identical with only a Map field keyValuePairs :V1.javaV2.java中,两者都与仅 Map 字段keyValuePairs相同:

public class V1 {
  Map<String, String> keyValuePairs;
}

Example of my json string:我的 json 字符串示例:

{
  "displayName": "My Name",
  "id": "id123",
  "stepDetails": {
    "v1": {
      "key1": "val1",
      "key2": "val2"
    },
    "v2": {
      "key1": "val1",
      "key2": "val2"
    }
  }
}

When I try to convert my json string to my model using Gson, the displayName and id fields in MyModel are populated fine, but the maps inside the v1 and v2 objects are null. When I try to convert my json string to my model using Gson, the displayName and id fields in MyModel are populated fine, but the maps inside the v1 and v2 objects are null. This is what I'm currently doing:这就是我目前正在做的事情:

MyModel myModel = new Gson().fromJson(jsonString, MyModel.class);

I've looked at several SO posts but they all seem to suggest using some form of TypeToken such as:我看过几个 SO 帖子,但它们似乎都建议使用某种形式的TypeToken ,例如:

new Gson().fromJson(jsonString, new TypeToken<MyModel>(){}.getType());

I tried it but the map fields are still not populated.我试过了,但 map 字段仍未填充。

The V1 and V2 types are unnecessary, because in the JSON, the dictionaries you want are directly associated with the keys "v1" and "v2". V1V2类型是不必要的,因为在 JSON 中,您想要的字典直接与键“v1”和“v2”相关联。 Therefore, the types of the fields v1 and v2 should be Map<String, String> :因此,字段v1v2的类型应该是Map<String, String>

class MyModel {
    private String displayName;
    private String id;
    private StepDetails stepDetails;

    // getters...
}

class StepDetails {
    private Map<String, String> v1;
    private Map<String, String> v2;

    // getters...
}

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

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