【问题标题】:Retrofit gson converter for nested Json Object with Date property为具有 Date 属性的嵌套 Json 对象改造 gson 转换器
【发布时间】:2016-04-22 18:42:32
【问题描述】:

JSON 结构如下所示:

"blabla": 1234,
"blabla2": "1234",
"object": {
        "property1": "1234",
        "property2": "blablab",
        "property3": "12345",
        "property4": Date object,
    }
}

由于这种结构,我实现了一个自定义的反序列化器并在 TypeAdapter 中传递它:

.registerTypeAdapter(Date.class, new DateDeserializer())
                .registerTypeAdapter(GenericNotificationResponse.class, new NotificationDeserializer())
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
                .create();

public class NotificationDeserializer implements JsonDeserializer<GenericNotificationResponse> {
    @Override
    public GenericNotificationResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject content = json.getAsJsonObject();
        GenericNotificationResponse message = new Gson().fromJson(json, typeOfT);
        JsonElement notification = content.get("notification");
        if (message.mType == 1)
            message.mNotification = (new Gson().fromJson(notification, Model1.class));
        else if (message.mType == 2)
            message.mNotification = (new Gson().fromJson(notification, Model2.class));
        return message;
    }
}

内部对象的反序列化很顺利。直到最近,当我更改模型并开始接收 Date 对象时,如 JSON 结构中所示,最后一个属性。由于某种原因,它无法解析它并引发错误,因此由于以下几行,我在 TypeAdapter 中传递的 DateDeserializer 似乎没有被调用:

 message.mNotification = (new Gson().fromJson(notification, Model1.class));

message.mNotification = (new Gson().fromJson(notification, Model2.class));

DateDeserializer 可以工作,因为我在其他模型中使用它并且它可以解决问题。有什么方法可以对内部 json 对象中的日期属性进行反序列化?谢谢!

【问题讨论】:

    标签: android gson retrofit


    【解决方案1】:

    当你这样做时:

     message.mNotification = (new Gson().fromJson(notification, Model1.class));
    

    您正在使用没有 DateDeserializer 的新 Gson() 实例进行反序列化。

    试试这样的:

    new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer())            
                    .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
                    .create().fromJson(notification, Model1.class));
    

    显然 Model2 也是如此。

    【讨论】:

    • 我将获得我在上面创建的 GSON 的一个实例,并在 NotificationDeserializer 中使用它。它可以工作,谢谢 :)
    猜你喜欢
    • 2015-05-15
    • 2014-05-29
    • 2017-07-27
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多