简体   繁体   English

JSON解析:一键,多值

[英]JSON Parsing: One key, Multiple Values

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. 然后我想从每个字符串创建一个新的“Route”,并将每个“Route”存储在一个集合中。 But I'm not sure how to iterate over it.. (for this example, we can just say that each Route has just a name). 但我不知道如何迭代它..(对于这个例子,我们可以说每个Route只有一个名字)。

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, 我刚刚修改了你的代码,这将解析你指定的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));
        }

    }
}
  • Initially we are converting the json string to JSONArray object. 最初我们将json字符串转换为JSONArray对象。
  • Then we are parsing the JSONObject from the JSONArray . 然后我们从JSONArray解析JSONObject。 Here we have only one JSONObject so we used getJSONObject(0) . 这里我们只有一个JSONObject,所以我们使用了getJSONObject(0) If you have more than one JSONObject you can iterate the values using a loop. 如果您有多个JSONObject,则可以使用循环迭代值。
  • Then we are storing all the key values within the JSONObject in a String Array. 然后我们将JSONObject中的所有键值存储在String数组中。
  • Finally we are iterating the values for the keys. 最后,我们迭代键的值。

Output: 输出:

Latitude : 49.27755
Routes : 006, C23
Longitude : -123.12698
Name : EB DAVIE ST FS HOWE ST

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM