奇葩json结构解析--key是数字的json处理

时间:2021-06-19 03:49:06

json结构如下:

{
"ret": "ok",
"data": {
"57230": {
"cat_id": "57230",
"alpha": "",
"title": "一汽-大众奥迪",
"malpha": "Y",
"catpid": "57229",
"catType": "2",
"child": [
{
"cat_id": "57233",
"alpha": "A",
"title": "奥迪Q5",
"malpha": null,
"catpid": "57230",
"catType": "3",
"Priced": false
},
{
"cat_id": "126193",
"alpha": "A",
"title": "奥迪Q3",
"malpha": null,
"catpid": "57230",
"catType": "3",
"Priced": false
},
{
"cat_id": "126537",
"alpha": "A",
"title": "奥迪A3",
"malpha": null,
"catpid": "57230",
"catType": "3",
"Priced": false
},
{
"cat_id": "57231",
"alpha": "A",
"title": "奥迪A4L",
"malpha": null,
"catpid": "57230",
"catType": "3",
"Priced": false
},
{
"cat_id": "57232",
"alpha": "A",
"title": "奥迪A6L",
"malpha": null,
"catpid": "57230",
"catType": "3",
"Priced": true
}
]
},
"success": true
}
}

"data"下面的数字部分是个list,结构相同,但是数字可能会发生变化,因为公司业务原因,不可能在后台统一数字部分的内容,这种结构遂蛋疼。不能直接利用gson这种直接去处理,gsonformat生成也会parse err。

但是活得干,问题得解决,如何解决呢:

如下就是解决方式,注意红色部位,然后就可以处理数字对应的valuse的内容,利用gson去解析:

if ( !isNull( response ) )
{
try {
JSONObject jsonObject0 = new JSONObject(
response.trim() );
JSONObject jsonObject = new JSONObject(
JsonUtil.getString( jsonObject0, "data" ) );
boolean isSuccess = JsonUtil.getBoolean( jsonObject,
"success" );
childEntities.clear();
if ( isSuccess )
{
Iterator<?> keys = jsonObject.keys();
while ( keys.hasNext() )
{
String key = (String) keys.next();
if ( jsonObject.get( key ) instanceof JSONObject )
{
String content =
jsonObject.get( key )
.toString();

PriceManagerResult.DataEntity.ChildEntity
childEntity = Json.get()
.toObject( content,
PriceManagerResult.DataEntity.ChildEntity.class );
childEntities.add( childEntity );
}
}
}
KLog.i( childEntities.size() );
mPriceManagerAdapter2.notifyDataSetChanged();
} catch ( JSONException e ) {
e.printStackTrace();
}
}