java使用Gson将JSON反序列化为非静态嵌套类
根据this,Gson可以反序列化到内部类。下面是JSON字符串的下一个片段:
...
"coordinates": {
"coordinates": [106.80552006,-6.22016938],
"type": "Point",
}
...
我用的是下一节课:
public class Tweet {
public Coordinates coordinates = new Coordinates();
public class Coordinates {
public double[] coordinates;
}
}
并尝试解析my JSON字符串:
Tweet tweet = gson.fromJson(string, Tweet.class);
Tweet.Coordinates tweetCoordinates = gson.fromJson(string, Tweet.Coordinates.class);
但我有一个错误:
Expected BEGIN_ARRAY but was BEGIN_OBJECT
你能告诉我错误在哪里吗
# 1 楼答案
当我将Gson用于嵌套类时,我总是需要使它们
static
工作。。。在你的链接中,他们说没有必要,但在Gson documentation中,他们明确地说:无论如何,如果反序列化到一个非静态的内部类是可能的,那么你的问题是
首先,用类
Tweet
解析JSON,方法是:这应该是有效的,因为类
Tweet
匹配JSON响应。然而,然后您试图用类Coordinates
解析相同的JSON响应,这显然与JSON响应不匹配。。。此外,对同一个响应进行两次解析也毫无意义如果您的第一次解析确实有效,那么如果您想访问
Coordinates
对象,只需执行以下操作:如果类
Tweet
的解析也不起作用,请尝试使内部类static
,如果这也不起作用,请评论,我将尝试找到另一个解决方案