【问题标题】:Exception happened when deserialize json based on class, the class have an interface type inside基于类反序列化json时发生异常,类内部有接口类型
【发布时间】:2012-12-26 23:50:53
【问题描述】:

我得到了 json 文件和第三方类:Dealer 和接口 IDealerAttributes(我不能改变它们中的任何一个); (我删除了包名和导入以简化代码)

JSON文件 { "serviceURL": "com.mycompany.serviceURL", “经销商属性”:[ { “语言”:“语言0”, "dealerAttributeName": "dealerAttributeName0", “更新日期”:0 }, { “语言”:“语言 1”, "dealerAttributeName": "dealerAttributeName1", “更新日期”:1 } ] } 类经销商{ 私有字符串服务URL; 私有列表dealerAttributes; 公共经销商(){ 经销商属性 = 新的 ArrayList(); } //Getter 和 Setter... } 公共接口 IDealerAttributes { 公共字符串 getLanguage(); 公共字符串 getDealerAttributeName(); 公共长 getUpdateDate(); }

我用过一次:

gson.fromJson(jsonObj.toString(), Dealer.class);

我会从这一行得到异常:

将 json 字符串解组为对象的异常:com.google.gson.JsonParseException:JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@60e26ffd 无法反序列化 json 对象 [{"language":"language0","dealerAttributeName":"dealerAttributeName0" ,"updateDate":0},{"language":"language1","dealerAttributeName":"dealerAttributeName1","updateDate":1}] 给定类型 java.util.List

如何根据 Dealer.class、IDealerAttributes 读取这个 json 文件?

但是我可以添加一个类,比如说:

公共类 DealerAttributes 实现 IDealerAttributes { 私有字符串语言; 私人字符串经销商属性名称; 私人长更新日期; 公共 DealerAttributes() { } //Getter 和 Setter... }

由于我是 json/gson 的新手,请您提供详细说明以帮助我吗?谢谢。

[添加] 考虑 Dealer 类中是否有 100 个字段,并且在 Dealer 中使用/嵌套了另外 100 个接口。我在想是否有人有使用这种方式的经验:(MyType is interface)

gson.registerTypeAdapter(MyType.class, new MyType());`

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    您可以将其映射到地图列表,然后使用像 http://code.google.com/p/orika/ 这样的 BeanMapper 来获取更多信息性错误消息

    【讨论】:

    • 能否请您提供一些更详细的说明?谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    相关资源
    最近更新 更多