joepetrakovich
joepetrakovich

Reputation: 1366

How would I model a Gson object that can handle a dynamic field?

An API my application is communicating with sends responses that look like:

{
    Code: 200,
    Message: "HELLO",
    Data: []
}

The Data field is always an array of SOMETHING. But that something could be a single node of text, another array of something else, or any other of an assortment of different objects.

In the below example, the data node is an array of an array of car objects.

Data: [ [ {car:1}, {car:2} ] ]

Another return type could be an array of insect objects:

Data: [ {insect : spider} ]

I would like to design a Gson object to handle this and was wondering what the best way would be.

My first thought is to have an abstract class that holds the Code and Message fields, and then have many sub-types that all have their own Data field. Then I would just call .fromJson() passing it the sub-class.

Is there a more optimal way to design it so that Gson would handle the differences?

Upvotes: 1

Views: 960

Answers (2)

joepetrakovich
joepetrakovich

Reputation: 1366

I figured out what I believe is the best answer. Fairly straightforward!

Make the class generic and supply the type by creating a TypeToken before passing to Gson:

   public class Response<T> {

        private String code;
        private String message;
        private List<T> data;
    }

Then when using Gson:

   Type myCarListResponse = new TypeToken<Response<List<Car>>>(){}.getType();
   Response<List<Car>> response = gson.fromJson(json, myCarListResponse);

Replace > with the type you are expecting from the Data node. The above example satisfies the first example from the original post.

To satisfy the second example:

  Type myInsectResponse = new TypeToken<Response<Insect>>(){}.getType();
  Response<Insect> response = gson.fromJson(json, myInsectResponse);

Upvotes: 3

Browny Lin
Browny Lin

Reputation: 2507

In Jackson, you can use @JsonAnyGetter/Setter to achieve this.

Refer http://www.cowtowncoder.com/blog/archives/2011/07/entry_458.html, http://wiki.fasterxml.com/JacksonFeatureAnyGetter

Upvotes: 0

Related Questions