Reputation: 47
I need to create a custom Gson deserializer that will when called recursively go into objects and deserialize them with the same concept
For this example let's create a JSON object:
{
"name": "Hello world!",
"foo": {
"bar": [12, 13, 14],
"type": "A"
}
}
And then classes, for this demonstration there are 2 classes MainOutputClass gets called from de-serializer, and de-serializer should de-serialize SubClass from foo
object in JSON
as for @ExposeAs()
this is for telling the de-serializer which JSON object to take.
public class MainOutputClass {
@ExposeAs("name")
private String nameString;
@ExposeAs("foo")
private SubClass subClass;
}
And finally subclass for recursive demonstration:
public class SubClass {
@ExposeAs("bar")
private List<Integer> bars;
@ExposeAs("type")
private String type;
}
I managed to create a de-serializer that can de-serialize the Main target class perfectly, but I can't seem to make it so that it would work on non-primitive subclasses.
I know this is a very weird question but I can't find any resources to figure this out. Any help is appreciated, thanks for taking your time to read this.
Upvotes: 0
Views: 202
Reputation: 2393
OP was looking for @SerializedName annotation which is used to translate the name as it should exist in the JSON format vs. what the field name is in Java.
For posterity, if you use Jackson parser, you can use @JsonProperty to the same effect.
When is the @JsonProperty property used and what is it used for?
Upvotes: 1
Reputation: 47
As pointed out by Atmas all I need to do was add @SerializedName
annotation to the fields.
Upvotes: 0