Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...