解析JSON文件Java

解析JSON文件Java,第1张

解析JSON文件Java

使用json.org参考实现(org.json主页,在此处下载)。代码有点混乱,但是我认为它可以满足您的要求。通过不创建所有这些对象而是直接访问它们,可以采用很多快捷方式。我这样做的原因是试图使其更容易跟踪发生的事情。

package com.mypackage;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;public class Main {    public static void main(String[] args) {        String jsonStr = "{"status": "OK","origin_addresses": [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],"destination_addresses": [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],"rows": [ {"elements": [ {"status": "OK","duration": {"value": 340110,"text": "3 jours 22 heures"},"distance": {"value": 1734542,"text": "1 735 km"}}, {"status": "OK","duration": {"value": 24487,"text": "6 heures 48 minutes"},"distance": {"value": 129324,"text": "129 km"}} ]}, {"elements": [ {"status": "OK","duration": {"value": 288834,"text": "3 jours 8 heures"},"distance": {"value": 1489604,"text": "1 490 km"}}, {"status": "OK","duration": {"value": 14388,"text": "4 heures 0 minutes"},"distance": {"value": 135822,"text": "136 km"}} ]} ]}";        try { JSonObject rootObject = new JSonObject(jsonStr); // Parse the JSON to a JSonObject JSonArray rows = rootObject.getJSonArray("rows"); // Get all JSonArray rows for(int i=0; i < rows.length(); i++) { // Loop over each each row     JSonObject row = rows.getJSonObject(i); // Get row object     JSonArray elements = row.getJSonArray("elements"); // Get all elements for each row as an array     for(int j=0; j < elements.length(); j++) { // Iterate each element in the elements array         JSonObject element =  elements.getJSonObject(j); // Get the element object         JSonObject duration = element.getJSonObject("duration"); // Get duration sub object         JSonObject distance = element.getJSonObject("distance"); // Get distance sub object         System.out.println("Duration: " + duration.getInt("value")); // Print int value         System.out.println("Distance: " + distance.getInt("value")); // Print int value     } }        } catch (JSonException e) { // JSON Parsing error e.printStackTrace();        }    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5642536.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存