java - 使用 Gson 将 JSON 反序列化为非静态嵌套类

标签 java json parsing gson

根据 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;
  }
}

并尝试解析我的 JSON 字符串:

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

但是我得到这个错误:

Expected BEGIN_ARRAY but was BEGIN_OBJECT

你能告诉我错误在哪里吗?

最佳答案

当我将 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,如果这也不起作用,请发表评论,我将尝试找到另一种解决方案...

关于java - 使用 Gson 将 JSON 反序列化为非静态嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16574998/

相关文章:

java - 更改 Hibernate 中的默认 IdentifierGenerator

java - 改造解析 JSON 响应空值 Android

c# - 使用ANTLR用C#解析C++

c++ - 解析 CSS 样式表

c# - 为什么 Roslyn 每种语言都有两个版本的语法?

java - 如何设置 setLanguageHints

Java 网络服务扫描器

java - 删除 POJO 的 toString() 中的某些 JSONObject 键

java - 使用批量API将数据加载到Elasticsearch v7.3

java - _version、_id 等的 spring-data-elasticsearch 元数据注释