java - 使用 GSON 时不兼容的类型

标签 java json gson

首先:这是我第一次使用 GSON。

尝试解析一些 JSON,我得到“不兼容的类型”...

Gson gson = new Gson();
PlayerData data = gson.fromJson(response, PlayerData.class); // Incompatible types...

PlayerData是一个内部类:

class PlayerData {
    public Point position;
    public String mapname;
    public int level;

    public PlayerData() {}
}

什么原因造成的?在GSON文档中显然有一个方法public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException我在(AFAIK)所做的就像 Google 在其 GSON 用户指南中一样。

编辑:
当我尝试用 Terminal 编译它时,XCode 做了一些奇怪的事情。一切正常,除了我对服务器的请求,这导致了几个 NPE,因为 response仍然是空的。感谢 maaartinus,我了解到不应该出现编译器错误,因此我尝试在不使用 XCode 的情况下编译它。

最佳答案

尝试将您的内部类设置为静态,否则您将需要一个自定义InstanceCreator,如 Gson User Guide 中所述。

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.

关于java - 使用 GSON 时不兼容的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12527077/

相关文章:

java - FTP 连接输入流挂起

java - Spring Data 存储库实际上是如何实现的?

asp.net - 序列化“System.Reflection”类型的对象时检测到循环引用

java - 如何在Jquery中将servlet发送的arraylist数据解析为JSON

java - GSON 可以用来检查对象相等性而不是覆盖 POJO 类的 equals 吗?

java - Gson Java - JSON 的子类

java - 在 cassandra 主数据库中包含枚举列是否会影响 cassandra 负载平衡?

java - 将 DataHandler 转换为 byte[]

json - 除了下面之外,还有其他方法可以将 json.rows 文件加载到 RStudio 中吗?

Android:用gson解析raw文件夹中的JSON文件?