Search code examples
jsonpojo

Gson (Json) parsing - POJO mapping - error (this is not a JSON Array)


For -

Config rfqObj = new Gson().fromJson(data, new TypeToken<Config>() {}.getType());

I'm getting the following exception -

The JsonDeserializer main.java.com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@30de3c87 failed to deserialized json object {} given the type main.java.com.google.gson.ParameterizedTypeImpl@7c3d0336] with root cause java.lang.IllegalStateException: This is not a JSON Array.

JSON data is -

{
  "quantities": {
    "142": "0",
    "143": "20",
    "144": "25"
  },
  "characteristics": {},
  "details": {
    "8": "HT Test Report",
    "9": "Others",
    "13": "nTest"
  },
  "materials": {},
  "additionalProcesses": {},
  "suppliers": {}
}

And here is the POJO -

public class Config {
Map<Long, String> quantities = new HashMap<Long, String>();
Map<Long, String> characteristics = new HashMap<Long, String>();    
Map<Long, String> details = new HashMap<Long, String>();
Map<Long, String> materials = new HashMap<Long, String>();
Map<Long, String> additionalProcesses = new HashMap<Long, String>();

public Set<Suppliers> suppliers = new HashSet();

//this is for the nested class
public static class Suppliers {
    // defining attributes of this class
    public Long id;
    public String name;
    public Long contactId;
    public String contactInfo;
    public String contactMethod;
    public String contactName;
    public String message;
}
}

Solution

  • The reason you are getting the error is that your JSON text is an object with the following property:

    "suppliers": {}
    

    But because your Config object wants the property suppliers to be a set; Gson is expecting a JSON array, not a JSON object.

    If you can somehow get your JSON text to include

    "suppliers": []
    

    you should be able to deserialize this into a Java set.