0

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.

Gaeini
  • 31
  • 5
  • 1
    I don't understand. Gson is recursive by design, so you shouldn't need to create anything custom to support it. Also it supports mapping custom names using @SerializedName annotation. Can you provide a specific example where you're NOT seeing it do that? – Atmas Mar 21 '21 at 00:52
  • This completely solves my problem, I don't know how I missed @SerializedName annotation. Thanks! – Sebastijan Kelneric Mar 21 '21 at 01:05
  • Hah. I didn't realize that was the answer you were looking for. :-) Glad I could help! I'll throw it below if you want to mark my answer for some kudos points. – Atmas Mar 21 '21 at 02:44

2 Answers2

1

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?

Atmas
  • 2,389
  • 5
  • 13
0

As pointed out by Atmas all I need to do was add @SerializedName annotation to the fields.