用改造和Gson反序化奇怪的json

时间:2016-05-10 20:59:34

标签: android json gson retrofit2

我需要反序化这个json:

  A    B       C  
2000  700  2/14/1999  
1500  750   1/1/2001  
1700  720   5/6/2000  
3000  680   7/8/1999  
4000  650   8/9/1999  

但是使用改装和Gson似乎是不可能的。

    {    
    "17": {
       "entity_id": "17",
       "attribute_set_id": "4",
       "type_id": "virtual",
       },
    "18": {
       "entity_id": "18",
       "attribute_set_id": "9",
       "type_id": "virtual"
       }
    }

那么,我该如何反序化这个生物呢?我可以使用哪种类型?

2 个答案:

答案 0 :(得分:0)

这是"17"是关键字和

的地图

{ "entity_id": "17", "attribute_set_id": "4", "type_id": "virtual", }

是一个对象。

尝试HashMap。

答案 1 :(得分:0)

你可以创建一个Java类(比如Item)来包含成员变量(entity_idattribute_set_idtype_id) - 我创建了this Gist,并且使用JSONObject做这样的事情:

JSONObject yourJSON = new JSONObject(jsonString);
//This will iterate through 17, 18, etc
Iterator<String> keysIterator = yourJSON .keys();
while(keysIterator.hasNext()) {
   String key = keysIterator.next();
   JSONObject actualObj = (JSONObject)yourJSON.get(key);
   //Here, supposing you had defined Item class, using Gson, you'd do this:
   Item thisItem = (new Gson()).fromJson(actualObj.toString(), Item.class);
   //From here you can call thisItem.getEntityId(), etc 
}
相关问题