【问题标题】:How can I use the Gson to parse a json that keep the same key but not the same type如何使用 Gson 解析保持相同键但不同类型的 json
【发布时间】:2015-05-19 14:27:29
【问题描述】:

其实,我想这样解析json:

{
"contents": [
    {
        "type": "image", 
        "data": {
            "attachment": "picurl", 
            "width": 600, 
            "height": 398
        }
    }, 
    {
        "type": "text", 
        "data": "something like xxx"
    }
]

}

如您所见,关键的“数据”有时是一个String,而sometings是json对象,我应该怎么做才能让Gson解析这个json?

【问题讨论】:

  • 使用自定义反序列化器怎么样?
  • 我会试试的!

标签: json gson


【解决方案1】:

我这样做的方式是反序列化两次。首先进入一个只定义type的类。

class TypeObject {
    public String type;
}

第一次反序列化后,您可以阅读type,并发现您应该反序列化到哪个真正的目标对象。

反序列化两次显然并不理想,但这是使用静态语言反序列化列表中具有非统一对象的 JSON 字符串的不幸性质。

【讨论】:

    【解决方案2】:

    我已经找到了解析 json 的方法,正如Alexis C 所说,我自定义了一个反序列化器,就像那样

    @Override
    public MessageDiv deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        MessageDiv messageDiv = new MessageDiv();
        JsonObject obj = jsonElement.getAsJsonObject();
        String msgtype = obj.get("type").getAsString();
        messageDiv.setType(msgtype);
        if (msgtype.equals("text")) {
            messageDiv.setContent(obj.get("data").getAsString());
        } else {
            JsonObject imgObj = obj.get("data").getAsJsonObject();
            DivData dd = new DivData();
            dd.setAttachment(imgObj.get("attachment").getAsString());
            dd.setHeight(imgObj.get("height").getAsInt());
            dd.setWidth(imgObj.get("width").getAsInt());
            messageDiv.setData(dd);
        }
        return messageDiv;
    }
    

    关于如何自定义反序列化器,点击here,对我很有用!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      相关资源
      最近更新 更多