4

In my project I'm using GSON to serialize and deserialize objects. Often I get a list of objects as JSON from a server but I'm only interested in the first element of the list. Is it possible with @SerializedName to only fetch the first element of the list?

I think about something like this: @SerializedName("List[0]")

Or what would you recommend to only parse the first element and not the whole list?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Cilenco
  • 6,951
  • 17
  • 72
  • 152
  • Perhaps this would be useful: https://stackoverflow.com/questions/41323887/partial-gson-deserialization – msanford Aug 21 '17 at 13:14

1 Answers1

4

You should use a custom JsonDeserializer:

private class MyCustomDeserializer implements JsonDeserializer<MyModel> {

  @Override
  public MyCustomDeserializer deserialize(JsonElement json, Type type,
        JsonDeserializationContext context) throws JsonParseException {

    // initialize an instance of your model
    MyModel myModel = new MyModel();

    JsonArray jArray = (JsonArray) json; // get json array
    JsonObject jsonObject = (JsonObject) jArray.get(0); // get first object

    // do what you want with the first object
    myModel.setParameter(jsonObject.get("parameter").getAsInt());

    // ignore next json objects
    return myModel;
  } 
}

Then, initialize your Gson instance like this:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(MyModel.class, new MyCustomDeserializer());
Gson gson = gsonBuilder.create();
MyModel model = gson.fromJson(jsonString, MyModel.class);

If you want to exclude some fields from Serialization you need to declare them in your model as transient:

private transient String name; // will be ignored from Gson
lubilis
  • 3,942
  • 4
  • 31
  • 54