Geralt_Encore
Geralt_Encore

Reputation: 3771

Gson custom deserialization

I'm using Gson to create and parse JSON, but I've faced one problem. In my code I use this field:

@Expose
private ArrayList<Person> persons = new ArrayList<Person>();

But my JSON is formated like this:

persons:{count:"n", data:[...]}

Data is an array of persons.

Is there any way to convert this JSON into my class using Gson? Can I use a JsonDeserializer?

Upvotes: 3

Views: 4974

Answers (2)

Purushotham
Purushotham

Reputation: 3820

You can try below code to parse your json

String jsonInputStr = "{count:"n", data:[...]}";

Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson(jsonInputStr, JsonElement.class).getAsJsonObject();
List<Person> persons = gson.fromJson(jsonObj.get("data").toString(), new TypeToken<List<Person>>(){}.getType());

Upvotes: 5

Chris Kessel
Chris Kessel

Reputation: 5865

You'll need a custom deserializer (http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonDeserializer.html), something like:

  public static class MyJsonAdapter implements JsonDeserializer<List<Person>>
  {
    List<Person> people = new ArrayList<>();
    public List<Person> deserialize( JsonElement jsonElement, Type type, JsonDeserializationContext context )
      throws JsonParseException
    {
      for (each element in the json data array) 
      {
        Person p = context.deserialize(jsonElementFromArray,Person.class );
        people.add(p);
      }
    }
    return people;
  }

Upvotes: 6

Related Questions