解析JSON文件Java

13

我想在Java中解析一个JSON文件,并从下面提到的文件中获取以下值:

{
  "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"
      }
    } ]
  } ]
}

我想从每个元素中获取distance和duration的值字段。我该如何做到这一点?


1
请查看以下链接:https://dev59.com/d3E95IYBdhLWcg3wkeuq - aayoubi
org.json库非常适合简单解析JSON。这个视频展示了如何使用org.json解析JSON文件。希望能有所帮助。 - drorw
7个回答

10

使用 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();
        }
    }
}

6
  1. 创建一个反映JSON的类结构
  2. 使用像Jackson或GSON这样的库将JSON反序列化为您的类的实例。

如果您想要更具动态性的方法,上述框架也可以将其序列化为映射。


1

1

正如Bozho所说,创建反映JSON的类结构,然后按照以下方式使用jacson库:

参考Java解析JSON文件

ObjectMapper mapper = new ObjectMapper();
Projects projs =
mapper.readValue(new File("projects.json"),Projects.class);
ArrayList<Project> projects = projs.get("projects");
for (Project p : projects) {
ArrayList<String> description = p.getDescription();
for (String s : description) {
System.out.println(s);

0

你可以使用:

org.bson.Document d = org.bson.Document.parse("{ foo: \"bar\" }");

0

你可以使用类似 JSON-java 的库。

import org.json.JSONObject;

String jsonString = ...
JSONObject object = new JSONObject(jsonString);
String status = object.getString("status");

-1

是的,你可以使用Jacson来解析它,但有更简单的方法来做到这一点,那就是Jsonme库"import org.json.me",你不需要添加jar文件来使用它

     JSONObject obj = new JSONObject("{'var1':'val1','var2':200});
     String var1=obj.getString("var1");
     int var2=obj.getInt("var2");

是的,使用它更容易,但如果您的项目比较复杂,我建议您使用jacson库。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接