如何使用GSON解析变量名称JSON对象?

时间:2015-11-30 11:28:17

标签: java json gson

如何使用带有可变对象名称的GSON解析JSON? "路线"对象具有相同的结构,但名称不同。它有许多不同的名称,因为它反映了旅行线路。我试图将它直接读到Java类(Android,Retrofit),但我不会为布达佩斯的所有旅行线创建单一类。是否有可能以某种方式阅读它?

{
"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

提前致谢!

1 个答案:

答案 0 :(得分: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覆盖。