简体   繁体   中英

How can I deserialize JSON to an object with a HashMap attribute?

Right now I am using Gson to deserialize JSON to Object.

The JSON looks like this:

[
   {
      "hash":"c8b2ce0aacede58da5d2b82225efb3b7",
      "instanceid":"aa49882f-4534-4add-998c-09af078595d1",
      "text":"{\"C_FirstName\":\"\",\"ContactID\":\"2776967\",\"C_LastName\":\"\"}",
      "queueDate":"2016-06-28T01:03:36"
   }
]

And my entity object looks like this:

public class AppCldFrmContact {
    public String hash;
    public String instanceid;
    public HashMap<String,String> text; 
    public String queueDate;
}

If text was a String data type, everything would be fine. But then I wouldn't be able to access different fields as I want to.

Is there a way to convert given JSON to Object I want?

The error I am getting is: Expected BEGIN_OBJECT but was STRING at line 1 column 174 , which is understandable if it cannot parse it.

The code doing the parsing:

Type listType = new TypeToken<List<AppCldFrmContact>>() {
        }.getType();
List<AppCldFrmContact> contacts = gson.fromJson(response.body, listType);

For you expected result, JSON data should be like below format,

[
   {
      "hash":"c8b2ce0aacede58da5d2b82225efb3b7",
      "instanceid":"aa49882f-4534-4add-998c-09af078595d1",
      "text":{"C_FirstName":"","ContactID":"2776967","C_LastName":""},
      "queueDate":"2016-06-28T01:03:36"
   }
]

You are getting this error because text field is a JSON map serialized to the string. If it is an actual your data and not a just an example, you can annotate a field with @JsonDeserialize and write your own custom JsonDeserializer<HashMap<String,String>> which will make deserialization 2 times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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