midas
midas

Reputation: 1848

Deserializing JSON to non-static nested classes using Gson

According to this Gson can deserialize to inner classes. I have the next fragment of JSON string:

...
"coordinates": {
    "coordinates": [106.80552006,-6.22016938],
    "type": "Point",
}
...

I'm using the next class:

public class Tweet {
  public Coordinates coordinates = new Coordinates();

  public class Coordinates {
    public double[] coordinates;
  }
}

and trying to parse the my JSON string:

Tweet tweet = gson.fromJson(string, Tweet.class);
Tweet.Coordinates tweetCoordinates = gson.fromJson(string, Tweet.Coordinates.class);

But I get this error:

Expected BEGIN_ARRAY but was BEGIN_OBJECT

Could you please tell me where the mistake is?

Upvotes: 3

Views: 3795

Answers (1)

MikO
MikO

Reputation: 18741

When I used Gson with nested classes I always needed to make them static to work... In your link they say that it's not necessary, but in Gson documentation it's clearly said:

"Gson can also deserialize static nested classes. However, Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it."


Anyway, if it's actually possible deserialize to a non-static inner class, your problem would be that...

First you are parsing the JSON with your class Tweet with:

Tweet tweet = gson.fromJson(string, Tweet.class);

which should be working, since the class Tweet matches the JSON response. However, then you are trying to parse the same JSON response with the class Coordinates, which obviously doesn't match the JSON response... moreover it makes no sense at all to parse the same response twice!

If your first parsing is actually working, if you then want to access the Coordinates object, just do:

Tweet.Coordinates tweetCoordinates = tweet.getCordinates();

If the parsing with the class Tweet is not working either, try to make the inner class static, and if that doesn't work either, please comment and I'll try to find another solution...

Upvotes: 6

Related Questions