2015-11-30 44 views
2

如何使用帶有變量對象名稱的GSON來解析JSON? 「路線」對象具有相同的結構,但名稱不同。它有許多不同的名字,因爲它反映了旅遊線路。我試圖直接讀到Java類(Android,Retrofit),但是我不會爲布達佩斯的所有旅行線創建單個類。是否有可能以某種方式讀取它?如何使用GSON分析變量名JSON對象?

{ 
"version": 2, 
"status": "OK", 
"code": 200, 
"text": "OK", 
"currentTime": 1448881433747, 
"data": { 
    "limitExceeded": false, 
    "references": { 
     "routes": { 
      "BKK_9630": { 
       "id": "BKK_9630", 
       "shortName": "963", 
       "longName": null, 
       "description": "Hűvösvölgy | Nagykovácsi, Tisza István tér", 
       "type": "BUS", 
       "url": null, 
       "color": "1E1E1E", 
       "textColor": "FFFFFF", 
       "agencyId": "BKK", 
       "bikesAllowed": false 
      }, 
      "BKK_0630": { 
       "id": "BKK_0630", 
       "shortName": "63", 
       "longName": null, 
       "description": "Hűvösvölgy | Nagykovácsi, Tisza István tér", 
       "type": "BUS", 
       "url": null, 
       "color": "009FE3", 
       "textColor": "FFFFFF", 
       "agencyId": "BKK", 
       "bikesAllowed": false 
      } 
     }, 
     "trips": {}, 
     "alerts": {} 
    } 
} 
} 

完整的JSON響應: http://futar.bkk.hu/bkk-utvonaltervezo-api/ws/otp/api/where/search.json?query=Erd%C3%A9szh%C3%A1z

提前感謝!

回答

2

這是你的階級結構:

爲MyObject(主要對象):

public class MyObject{ 

    private Integer version; 
    private String status; 
    private Integer code; 
    private Data data; 
} 

數據

public class Data{ 

    private boolean limitExceeded; 
    private References references; 
} 

參考

public class References{ 

    private Map<String, Route> routes; 
} 

路線

public class Route{ 

    private String shortName; 
} 

然後:

String json = "{'version':2,'status':'OK','code':200,'text':'OK','currentTime':1448881433747,'data':{'limitExceeded':false,'references':{'routes':{'BKK_9630':{'id':'BKK_9630','shortName':'963','longName':null,'description':'Hűvösvölgy | Nagykovácsi, Tisza István tér','type':'BUS','url':null,'color':'1E1E1E','textColor':'FFFFFF','agencyId':'BKK','bikesAllowed':false},'BKK_0630':{'id':'BKK_0630','shortName':'63','longName':null,'description':'Hűvösvölgy | Nagykovácsi, Tisza István tér','type':'BUS','url':null,'color':'009FE3','textColor':'FFFFFF','agencyId':'BKK','bikesAllowed':false}},'trips':{},'alerts':{}}}}"; 
     Gson gson = new Gson(); 
     MyObject fromJson = gson.fromJson(json, MyObject.class); 
     System.out.println(fromJson); 

結果:

MyObject [version=2, status=OK, code=200, data=Data [limitExceeded=false, references=References [routes={BKK_9630=Route [shortName=963], BKK_0630=Route [shortName=63]}]]] 

需要注意的是,不是我寫的,你必須把它們寫所有領域。另外不要忘記創建getter and setterstoString覆蓋。

+0

現在,它的工作原理,謝謝! – akapitany