【问题标题】:Parsing JSON File Java [duplicate]解析 JSON 文件 Java [重复]
【发布时间】:2012-02-14 21:23:03
【问题描述】:

我想在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"
      }
    } ]
  } ]
}

我想从每个元素中获取距离和持续时间的值字段。我该怎么做?

【问题讨论】:

标签: java json parsing


【解决方案1】:

你可以使用:

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

【讨论】:

    【解决方案2】:

    使用 json.org 参考实现(org.json homepageDownload here)。代码有点乱,但我认为它可以满足您的要求。您可以通过不创建所有这些对象而是直接访问它们来采取很多快捷方式。我这样做的原因是为了更容易了解正在发生的事情。

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

    【讨论】:

      【解决方案3】:

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

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

      是的,它更容易,但如果您的项目很复杂,我建议您使用 jacson lib

      【讨论】:

        【解决方案4】:

        你可以使用像JSON-java这样的库

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

        【讨论】:

          【解决方案5】:

          正如 Bozho 所说,创建反映 JSON 的类结构,然后使用 jacson 库,如下所示:

          参考Parsing JSON File Java

          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);
          

          【讨论】:

            【解决方案6】:

            使用库来处理 JSON。例如google-gson

            【讨论】:

              【解决方案7】:
              1. 创建反映 JSON 的类结构
              2. 使用 Jackson 或 GS​​ON 等库将 json 反序列化为类的实例。

              如果您想要更动态的方法,上述框架也可以序列化为地图。

              【讨论】:

                猜你喜欢
                • 2013-02-19
                • 2019-06-09
                • 2021-07-14
                • 2013-02-28
                • 2011-06-12
                • 1970-01-01
                • 2020-09-30
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多