I want to deserialize json objects to specific types of objects (using Gson library) based on type
field value, eg.:
[
{
"type": "type1",
"id": "131481204101",
"url": "http://something.com",
"name": "BLAH BLAH",
"icon": "SOME_STRING",
"price": "FREE",
"backgroundUrl": "SOME_STRING"
},
{
....
}
]
So type
field will have different (but known) values. Based on that value I need to deserialize that json object to appropriate model object, eg.: Type1Model, Type2Model etc.
I know I can easily do that before deserialization by converting it to JSONArray
, iterate through it and resolve which type it should be deserialized to. But I think it's ugly approach and I'm looking for better way. Any suggestions?
@stephane-k 's answer works, but it is a bit confusing and could be improved upon (see comments to his answer)
Copy https://github.com/google/gson/blob/master/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java into your project. (It's ok; these classes are designed to be copy/pasted https://github.com/google/gson/issues/845#issuecomment-217231315)
Setup model inheritance:
Setup GSON or update existing GSON:
Deserialize your JSON into base class:
baseInstance
will be instanceof eitherType1Model
orType2Model
.From here you can either code to an interface or check instanceof and cast.
You may implement a
JsonDeserializer
and use it while parsing your Json value to a Java instance. I'll try to show it with a code which is going to give you the idea:1) Define your custom
JsonDeserializer
class which creates different instance of classes by incoming json value's id property:2) Define a base class for your different instance of java objects:
3) Define your different instance of java objects' classes which extend your base class:
4) Use these classes while parsing your json value to a bean:
I can not test it right now but I hope you get the idea. Also this link would be very helpful.
use https://github.com/google/gson/blob/master/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java
then configure it with
and add the annotation:
@JsonAdapter(MyBaseType.JsonAdapterFactory.class)
to MyBaseType
Much better.