我得到了 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/