简体   繁体   English

如何将JSON反序列化为具有HashMap属性的对象?

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

Right now I am using Gson to deserialize JSON to Object. 现在我正在使用Gson将JSON反序列化为Object。

The JSON looks like this: JSON看起来像这样:

[
   {
      "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. 如果textString数据类型,一切都会好的。 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? 有没有办法将给定的JSON转换为我想要的对象?

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. 我得到的错误是: Expected BEGIN_OBJECT but was STRING at line 1 column 174 ,如果它无法解析它是可以理解的。

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, 对于您预期的结果,JSON数据应该类似于以下格式,

[
   {
      "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. 您收到此错误,因为文本字段是序列化为字符串的JSON映射。 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. 如果它是一个实际的数据,而不仅仅是一个例子,你可以用@JsonDeserialize注释一个字段并编写你自己的自定义JsonDeserializer<HashMap<String,String>> ,它将进行2次反序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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