[英]JSON Parsing: One key, Multiple Values
我在如何解析以下數據方面遇到了一些麻煩:
[{
"Name": "EB DAVIE ST FS HOWE ST",
"Latitude": 49.27755,
"Longitude": -123.12698,
"Routes": "006, C23" }]
我想獲得“路線”的所有價值。 然后我想從每個字符串創建一個新的“Route”,並將每個“Route”存儲在一個集合中。 但我不知道如何迭代它..(對於這個例子,我們可以說每個Route只有一個名字)。
到目前為止,我有:
JSONObject stop = allStops.getJSONObject(i);
JSONArray array = stop.getJSONArray("Routes");
for(int i = 0; i < array.length(); i++) {
Route r = new Route(array.get(i)) // i thought (array.get(i)) would give you the String of each value (e.g. "006")
Set<Route> routes = new HashSet<Route>();
routes.add(array.get(i)); // then I thought I should just add each route
}
但這不起作用。 我不知道該怎么做。
String routes = stop.getString("Routes");
String[] split_routes = routes.split(", "); /*all routes will be stored in this array*/
你可以嘗試使用com.alibaba.fastjson.JSON,定義一個java類,然后像這樣:
List<MyClass> list= JSON.parseObject(jsonStr, new TypeReference<List<MyClass>>() {});
我剛剛修改了你的代碼,這將解析你指定的JSON格式,
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonParser {
public static void main(String[] args) throws Exception {
String jsonString = "[{\"Name\":\"EB DAVIE ST FS HOWE ST\",\"Latitude\":49.27755,\"Longitude\":-123.12698,\"Routes\":\"006, C23\"}]";
JSONArray arrayObject = new JSONArray(jsonString);
JSONObject inner = arrayObject.getJSONObject(0);
String[] keys = JSONObject.getNames(inner);
for(String entry : keys) {
System.out.println(entry+" : "+inner.get(entry));
}
}
}
getJSONObject(0)
。 如果您有多個JSONObject,則可以使用循環迭代值。 輸出:
Latitude : 49.27755
Routes : 006, C23
Longitude : -123.12698
Name : EB DAVIE ST FS HOWE ST
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.