Reputation: 108
JSON structure looks like the following:
"blabla": 1234,
"blabla2": "1234",
"object": {
"property1": "1234",
"property2": "blablab",
"property3": "12345",
"property4": Date object,
}
}
Due to this structure, I have implemented a custom deserializer and passed it in the 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;
}
}
And the deserialization of the inner object goes fine. Until recently, when I changed the model and started receiving a Date object as well, as shown in the JSON structure, the last property. For some reason, it cannot parse it and it throws an error, so it seems like the DateDeserializer that I'm passing in the TypeAdapter is not called due to the these lines:
message.mNotification = (new Gson().fromJson(notification, Model1.class));
message.mNotification = (new Gson().fromJson(notification, Model2.class));
The DateDeserializer works since I'm using it within other models and it does the trick. Is there any way I can make the deserialization of the date property in the inner json Object? Thank you!
Upvotes: 0
Views: 366
Reputation: 374
When you do this:
message.mNotification = (new Gson().fromJson(notification, Model1.class));
You are deserializing with a new Gson()
instance that does not have the DateDeserializer
.
Try something like this:
new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer())
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.create().fromJson(notification, Model1.class));
Same thing for Model2 obviously.
Upvotes: 1