2

Giving

JSON

// imagine this is JSON of a city
{
    "title" : "Troy"
    "people" : [
        {
            {
                "title" : "Hector",
                "status" : "Dead"
            },
            {
                "title" : "Paris",
                "status" : "Run Away"
            }
        },
        ...
    ],
    "location" : "Mediteranian",
    "era" : "Ancient",
    ...
}

City

public class City {
    @SerializeName("title")
    String title;
    @SerializeName("people")
    List<Person> people;
    @SerializeName("location")
    String location;
    @SerializeName("era")
    String era;
    ...
}

Person

public class Person {
    @SerializeName("title")
    private String title;
    @SerializeName("status")
    private String status;
}

If having string of JSON above, it is possible to create list of person

A. without having to deserialize City first like following

City city = new Gson().fromJson(json, City.class)
ArrayList<Person> people = city.people;

And

B. without having to convert string to JSONObject, get JSONArray and then convert back to string like following

String peopleJsonString = json.optJSONArray("people").toString
ArrayList<Person> people = new Gson().fromJSON(peopleJsonString, Person.class);

2 Answers 2

4

You can use a custom JsonDeserializer, which is part of Gson (com.google.gson.JsonDeserializer).

Simple example:

public class WhateverDeserializer implements JsonDeserializer<Whatever> {
  @Override
  public Whatever deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
    Whatever whatever = new Whatever();
    // Fetch the needed object here
    // whatever.setNeededObject(neededObject);
    return whatever;
  }
}

You can then apply this deserializer like this:

Gson gson = new GsonBuilder()
            .registerTypeAdapter(Whatever.class, new WhateverDeserializer())
            .create();

There is a full example of how to use a custom deserializer, including a super detailed explanation, on this page: http://www.javacreed.com/gson-deserialiser-example/

Sign up to request clarification or add additional context in comments.

Comments

0

I don't think you can get the list directly without parsing the json array. You need to parse the array. And it would be faster via Gson;

If you strictly need (only array) and you won't be using any other json object . Simply delete them, so that gson won't parse them.

1 Comment

Take a closer look to the question and the limitations that @Tar_Tw45 set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.