1
votes

I was given json file and third party class:Dealer and interface IDealerAttributes (I can not change either of them); (I remove package name and imports to make the code simple)


    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());`
1

1 Answers

1
votes

You could map it to a List of Maps and then use a BeanMapper like http://code.google.com/p/orika/ to get some more informative error messages