I have 2 class
class X {
public String name;
public int age;
}
class Y {
public float score;
}
The json is like this
{
"type": "X",
"data": {
"name": "myname",
"age": 20
}
}
or
{
"type": "Y",
"data": {
"score": 10
}
}
How to parse the json with gson but if the type field is X
then the data will be X
class instance
3
Answers
I found how after some questions to google bard...
Then I use it like this
But with this i dont know why i extend the
TypeAdapter<Object>
.. i dont think i need it.You want to deserialize the JSON according to the value of the type element. So you parse the JSON and extract the value of the type element. Then you extract the data element and use Gson to deserialize it to a Java object.
The above code uses text blocks that were added in Java 15.
I added a toString method to class
X
:When I run the above code, I get the following:
Note that one would usually make class
X
and classY
JavaBeans, i.e. you need to add "getters" and "setters".Here is a complete code:
Refer to Gson User Guide
if you don’t want to create custom adapter then try using map!
it could be one of the most simple solution