Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将生成的JSON数据读入Java?_Java_Json - Fatal编程技术网

如何将生成的JSON数据读入Java?

如何将生成的JSON数据读入Java?,java,json,Java,Json,我正在尝试将JSON请求的结果读入java,但是 我的JSON请求的部分输出如下所示: "route_summary": { "total_distance": 740, "total_time": 86, "start_point": "Marienstraße", "end_point": "Feldbergstraße" } 我想使用标准json库来提取总距离中的值。 然而,我似乎只能通过以下方式获得“路线摘要”:

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

"route_summary": {
        "total_distance": 740,
        "total_time": 86,
        "start_point": "Marienstraße",
        "end_point": "Feldbergstraße"
    }
我想使用标准json库来提取总距离中的值。 然而,我似乎只能通过以下方式获得“路线摘要”:

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\u summary
,就像您已经做的那样,并且您需要从该对象获得
总距离。这将返回
路线摘要。总距离

代码示例:

    JSONObject object = new JSONObject(s);
    int totalDistance = object.getJSONObject("route_summary").getInt("total_distance");

您需要获得
route\u summary
,就像您已经做的那样,并且需要从该对象获得
总距离。这将返回
路线摘要。总距离

代码示例:

    JSONObject object = new JSONObject(s);
    int totalDistance = object.getJSONObject("route_summary").getInt("total_distance");

我建议您使用GSON图书馆。您可以创建表示消息的类,然后通过调用函数将JSON自动映射到对象:
gson.fromJson(message,YourMessageClass.class).getRoute_summary()


下面是这种方法的示例:

我建议您使用GSON库。您可以创建表示消息的类,然后通过调用函数将JSON自动映射到对象:
gson.fromJson(message,YourMessageClass.class).getRoute_summary()


下面是这样一个例子:

你说“在部门”。您提供的json字符串是更大json对象的一部分吗?您可以说“in dept”。您提供的json字符串是较大json对象的一部分吗?为什么建议使用GSON?性能更好吗?(我似乎有功能性的JSON查询,因此看不出有什么区别)为什么建议使用GSON?性能更好吗?(我似乎有功能性的JSON查询,因此看不出有什么区别)