有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    当我将Gson用于嵌套类时,我总是需要使它们static工作。。。在你的链接中,他们说没有必要,但在Gson documentation中,他们明确地说:

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


    无论如何,如果反序列化到一个非静态的内部类是可能的,那么你的问题是

    首先,用类Tweet解析JSON,方法是:

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

    这应该是有效的,因为类Tweet匹配JSON响应。然而,然后您试图用类Coordinates解析相同的JSON响应,这显然与JSON响应不匹配。。。此外,对同一个响应进行两次解析也毫无意义

    如果您的第一次解析确实有效,那么如果您想访问Coordinates对象,只需执行以下操作:

    Tweet.Coordinates tweetCoordinates = tweet.getCordinates();
    

    如果类Tweet的解析也不起作用,请尝试使内部类static,如果这也不起作用,请评论,我将尝试找到另一个解决方案