java - 基于类反序列化json时发生异常,该类内部有一个接口(interface)类型

标签 java json gson

我得到了 json 文件和第三方类:Dealer 和接口(interface) IDealerAttributes (我无法更改其中任何一个); (我删除了包名称和导入以使代码简单)


    JSON file
    {
      "serviceURL": "com.mycompany.serviceURL",
      "dealerAttributes": [
        {
          "language": "language0",
          "dealerAttributeName": "dealerAttributeName0",
          "updateDate": 0
        },
        {
          "language": "language1",
          "dealerAttributeName": "dealerAttributeName1",
          "updateDate": 1
        }
      ]
    }

    class Dealer {
        private String serviceURL;
        private List dealerAttributes;

        public Dealer() {
            dealerAttributes = new ArrayList();
        }

        //Getters and Setters...
    }

    public interface IDealerAttributes {
        public String getLanguage();
        public String getDealerAttributeName();
        public long getUpdateDate();
    }

once I use:


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

I will get exception from this line:

Exception unmarshalling json String into Object: com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@60e26ffd failed to deserialize json object [{"language":"language0","dealerAttributeName":"dealerAttributeName0","updateDate":0},{"language":"language1","dealerAttributeName":"dealerAttributeName1","updateDate":1}] given the type java.util.List

How can I read this json file based on Dealer.class, IDealerAttributes?

But I can add one class, let's say:


    public class DealerAttributes implements IDealerAttributes {
        private String language;
        private String dealerAttributeName;
        private long updateDate;

        public DealerAttributes() { 
        }

        //Getters and Setters...
    }

Since I am new to json/gson, would you please give detailed instruction to help me out? Thanks.

[added] Consider if there are 100 fields in Dealer class, and there are another 100 interface used/nested in Dealer. I am thinking whether anyone have experience using this way: (MyType is interface)

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

最佳答案

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

关于java - 基于类反序列化json时发生异常,该类内部有一个接口(interface)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14294401/

相关文章:

java - Jackson 和 Gson 中使用 json 路径的地址元素

android - 使用 Retrofit 处理变量 JSON

java - 如何判断 GraphicsEnvironment 是否存在

java - 检查 json 属性是否存在,是否为字符串,是否为正确的值

java - 命名包的更好方法是什么

arrays - 具有多个数组的 PowerShell ConvertTo-JSON

jquery - 如何使用 PHP 将值从 json_encode 传递到 Ajax

javascript - 如何设置安全规则以防止删除 firebase 中的数据?

java - 如何在 Kafka 集成测试中通过发送消息来设置应用程序状态?

java - JTable 更改 BoxLayout 上其他组件的位置