gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:43:56 24 4
gpt4 key购买 nike

如何使用具有可变对象名称的 GSON 解析 JSON? “路线”对象具有相同的结构,但名称不同。它有许多不同的名称,因为它反射(reflect)了旅行线路。我正在尝试将其直接读入 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

提前致谢!

最佳答案

这是你的类结构:

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 和 settertoString 覆盖。

关于java - 如何使用 GSON 解析变量名 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33997562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com