Ondrej Tokar Ondrej Tokar - 3 months ago 7
Java Question

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:


And my entity object looks like this:

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

was a
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>>() {
List<AppCldFrmContact> contacts = gson.fromJson(response.body, listType);


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.