I'm having a little bit of trouble with how to parse the following data:
[{
"Name": "EB DAVIE ST FS HOWE ST",
"Latitude": 49.27755,
"Longitude": -123.12698,
"Routes": "006, C23" }]
I would like to get all the values of "Routes". Then I would like to create a new "Route" from each string, and store each "Route" in a set. But I'm not sure how to iterate over it.. (for this example, we can just say that each Route has just a name).
So far I have:
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
}
but this doesn't work. I'm not sure what to do.
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>>() {});
I just modified your code, this will parse your specified JSON format,
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)
. If you have more than one JSONObject you can iterate the values using a loop. Output:
Latitude : 49.27755
Routes : 006, C23
Longitude : -123.12698
Name : EB DAVIE ST FS HOWE ST
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.