Search code examples
javagsonmoxy

Parsing this weird nested hashmap with Gson


I have an object with the following fields, which I'm trying to parse, coming from a webservice:

private String serviceGroup;
private String serviceDefinition;
private List<String> interfaces = new ArrayList<>();
private Map<String, String> serviceMetadata = new HashMap<>();

For some reason, the json has this object with a format like this:

"service": {
 "interfaces": [
    "json"
  ],
  "serviceDefinition": "IndoorTemperature",
  "serviceGroup": "Temperature",
  "serviceMetadata": {
    "entry": [
      {
        "key": "security",
        "value": "token"
      },
      {
        "key": "unit",
        "value": "celsius"
      }
    ]
  }
}

The extra, unneeded part here is that "entry" array at the serviceMetadata Hashmap. So when I'm trying to parse the json into my object with Gson.fromJson(theString, myclass.class), I get a com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY exception. What could I do to parse the hashmap?

By the way the webservice uses moxy to marshal the objects.


Solution

  • You defined serviceMetadata as new HashMap<String, String>()

    But it should be Map of lists of objects

    Your key is entry and List is:

              [{
                    "key": "security",
                    "value": "token"
                }, {
                    "key": "unit",
                    "value": "celsius"
                }]
    

    So the solution is - create some class Entry:

    public class Entry{
      private String key;
      private String value;
    }
    

    And now:

    private Map<String, List<Entry>> serviceMetadata = new HashMap<>();