首先:这是我第一次使用 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/