【发布时间】: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 对象中的日期属性进行反序列化?谢谢!
【问题讨论】: