2012-01-20 37 views
12

Tôi muốn phân tích một tệp JSON trong java và nhận được các giá trị sau từ tập tin đề cập dưới đây:Parsing JSON file Java

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

Từ mọi yếu tố, tôi muốn để có được những lĩnh vực giá trị của cả hai khoảng cách và thời gian . Làm thế nào để tôi làm điều này?

+1

việc kiểm tra này: http://stackoverflow.com/questions/2255220/how-to-parse-a-json-and-turn-its-values- thành một mảng – aayoubi

Trả lời

10

Sử dụng thực hiện tham chiếu json.org (org.json homepage, Download here). Mã này hơi lộn xộn nhưng tôi nghĩ nó làm những gì bạn đang yêu cầu. Bạn có thể thực hiện rất nhiều phím tắt bằng cách không tạo tất cả các đối tượng này nhưng để truy cập chúng trực tiếp. Lý do tôi làm theo cách này là một nỗ lực để làm cho nó dễ dàng hơn để làm theo những gì đang xảy ra.

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. Tạo một cấu trúc lớp phản ánh JSON
  2. Sử dụng thư viện như Jackson hay GSON để deserialize các json với các trường hợp lớp học của bạn.

Nếu bạn muốn tiếp cận năng động hơn, các khuôn khổ trên cũng có thể tuần tự hóa thành bản đồ.

1

như Bozho nói tạo cấu trúc lớp reflacts JSON và sau đó sử dụng thư viện jacson như sau:

tham khảo 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); 
0

Bạn có thể sử dụng một thư viện như JSON-java

import org.json.JSONObject; 

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

có bạn có thể sử dụng jacson để phân tích cú pháp nhưng có cách dễ dàng hơn để làm điều đó lib Jsonme của nó "import org.json.me" bạn không cần phải quảng cáo d file jar để sử dụng nó

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

có của nó dễ dàng hơn, nhưng nếu dự án của bạn rất phức tạp tôi lời khuyên bạn sử dụng jacson lib

0

Bạn có thể sử dụng:

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