【发布时间】:2015-10-10 17:45:35
【问题描述】:
我只需要一个快速的建议,因为我是 JSON 的初学者。
我从网络服务器得到以下响应,我将其存储在字符串中:
{
"station62":[
{
"departureTime":1982,
"delay":"-1.0",
"line":"6",
"stationName":"randomname",
"direction":2
}
],
"station63":[
{
"departureTime":1234,
"delay":"-1.0",
"line":"87",
"stationName":"anotherrandomname",
"direction":2
}
],
"station64":[
{
"departureTime":4542,
"delay":"-1.0",
"line":"4",
"stationName":"yetanotherrandomname",
"direction":2
}
],
"station65":[
{
"departureTime":1232,
"delay":"-1.0",
"line":"23",
"stationName":"onemorerandomname",
"direction":2
}
]
}
(对不起,我不知道这里的缩进是如何工作的。)
响应更长,但在本例中它被缩短了。所以我需要解析每个“站”对象的信息。 我不需要“station62”-String,我只需要 java-object 中的“departureTime”、“delay”、“line”、“stationName”和“direction”。
我已阅读此内容,但无法正常工作:https://stackoverflow.com/a/16378782
我是一个完全的初学者,所以非常感谢任何帮助。
编辑:这是我的代码:
我制作了一个包装类,就像上面的示例链接一样。我玩过一些地图类型,但到目前为止没有运气。
public class ServerResponse
{
private Map<String, ArrayList<Station>> stationsInResponse = new HashMap<String, ArrayList<Station>>();
public Map<String, ArrayList<Station>> getStationsInResponse()
{
return stationsInResponse;
}
public void setStationsInResponse(Map<String, ArrayList<Station>> stationsInResponse)
{
this.stationsInResponse = stationsInResponse;
}
}
问题是,这张地图没有被我在下面显示的 gson.fromJSON(...) 调用填充。地图大小始终为零。
Station 类如下所示:
public class Station
{
String line;
String stationName;
String departureTime;
String direction;
String delay;
// getters and setters are there aswell
}
而我想做的是
Gson gson = new Gson();
ServerResponse response = gson.fromJson(jsonString, ServerResponse.class);
其中“jsonString”包含 JSON 响应作为字符串。
我希望代码能显示我需要做什么,它应该很简单,但我在 JSON 中还不够好。
编辑 2
我需要这样的 JSON 吗?
{"stationsInResponse": {
"station62": [{
"departureTime": 1922,
"delay": "-1.0",
"line": "8",
"stationName": "whateverrandomname",
"direction": 2
}],
"station67": [{
"departureTime": 1573,
"delay": "-1.0",
"line": "8",
"stationName": "rndmname",
"direction": 2
}],
"station157": [{
"departureTime": 1842,
"delay": "-2.0",
"line": "8",
"stationName": "randomname",
"direction": 2
}]
}}
【问题讨论】:
-
在您提到的答案的帮助下,您到目前为止所做的尝试。
-
您应该在此处添加您的代码,以便我们为您提供帮助。
-
我添加了一些代码,谢谢。
-
但响应不是
ServerResponse的类型,而是HashMap<String, ArrayList<Station>>...在json中没有归档stationsInResponse -
所以我需要为我的地图提供与我的 JSON 文件中的名称相同的名称吗?问题是,我的 JSON 文件中的所有站点都被称为不同的站点,例如“station96”、“station 120”等等。
标签: java android json parsing gson