Home > Net >  How to convert json to nested Maps using Gson?
How to convert json to nested Maps using Gson?

Time:08-21

I have a POJO MyModel.java:

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

In StepDetails.java I have:

public class StepDetails {
  V1 v1;
  V2 v2;
}

In V1.java and V2.java, both are identical with only a Map field keyValuePairs:

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

Example of my json string:

{
  "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. 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:

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

I tried it but the map fields are still not populated.

CodePudding user response:

The V1 and V2 types are unnecessary, because in the JSON, the dictionaries you want are directly associated with the keys "v1" and "v2". Therefore, the types of the fields v1 and v2 should be 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...
}
  • Related