0

我正在尝试将 JSON 请求的结果读入 java,但我的 JSON 请求的部分输出如下所示:

"route_summary": {
        "total_distance": 740,
        "total_time": 86,
        "start_point": "Marienstraße",
        "end_point": "Feldbergstraße"
    }

我想使用标准 json 库来提取 total_distance 中的值。但是,我似乎只能通过这样做来获得“route_summary”:

JSONObject json = null;
json = readJsonFromUrl(request);
json.get("route_summary");

在哪里

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            is.close();
        }
    }

我想要的是“进入” route_summary,任何线索/提示都会很棒!

4

2 回答 2

3

你需要得到route_summary,就像你已经做过的那样,并且从那个对象中你需要得到total_distance. 这将给您返回route_summary.total_distance.

代码示例:

    JSONObject object = new JSONObject(s);
    int totalDistance = object.getJSONObject("route_summary").getInt("total_distance");
于 2012-06-30T20:18:18.930 回答
0

I would recommend you to use GSON library. You can create class which will represent the message and then automatically map JSON to object by invoking function: gson.fromJson(message, YourMessageClass.class).getRoute_summary().

Here is the example of such approach: https://sites.google.com/site/gson/gson-user-guide/#TOC-Object-Examples

于 2012-06-30T20:18:47.423 回答