2016-05-10 36 views
1

反序列化JSON怪我需要反序列化JSON这样:与改造和GSON

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

,但使用改装和GSON这似乎是不可能的。

OkHttpClient client = new OkHttpClient.Builder() 
       .addInterceptor(new SigningInterceptor(consumer)) 
       .readTimeout(60, TimeUnit.SECONDS) 
       .connectTimeout(60, TimeUnit.SECONDS) 
       .build(); 

     retrofit = new Retrofit.Builder() 
       .baseUrl("http://endpoint/") 
       .client(client) 
       .addConverterFactory(GsonConverterFactory.create()) 
       .build(); 

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

+0

你可以在对象申报与entity_id和其他attr然后你的服务器响应类将只有该对象 –

回答

0

这是地图,"17"是一个关键和

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

是一个对象。

尝试使用HashMap。

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 
}