Monday, 2 September 2013

Gson: Custom deserialization if certain field is present

Gson: Custom deserialization if certain field is present

I have a class that looks as follows
class Person {
Long id;
String firstName;
int age;
}
and my input either looks like this:
{ "id": null, "firstName": "John", "age": 10 }
or like this:
{ "id": 123 }
The first variant represents a "new" (non-persisted) person and the second
refers to a person by its database id.
If id is non-null, I would like to load the object from database during
deserialization, otherwise fallback on regular parsing and deserialize it
as a new object.
What I've tried: I currently have a JsonDeserializer for
database-deserialization, but as I understand it, there is no way to "fall
back" on regular parsing. According to this answer I should use a
TypeAdapterFactory and the getDelegateAdapter. My problem with this
approach is that I'm given a JsonReader (and not for instance a
JsonElement) so I can't determine if the input contains a valid id without
consuming input.
Any suggestions on how to solve this?

No comments:

Post a Comment