2012-01-20 27 views
12

voglio analizzare un file JSON in java e ottenere i seguenti valori dal file di seguito indicate:di analisi 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" 
     } 
    } ] 
    } ] 
} 

Da ogni elemento, voglio ottenere il campo di valore sia di distanza e la durata . Come faccio a fare questo?

+1

controllo questo: http://stackoverflow.com/questions/2255220/how-to-parse-a-json-and-turn-its-values- in-un-array – aayoubi

risposta

10

Utilizzando l'implementazione di riferimento json.org (org.json homepage, Download here). Il codice è un po 'confuso, ma penso che faccia quello che stai chiedendo. Puoi prendere molte scorciatoie non creando tutti questi oggetti ma accedendoli direttamente. Il motivo per cui lo faccio in questo modo è un tentativo di rendere più facile seguire che cosa sta succedendo.

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. creare una struttura di classe che riflette il JSON
  2. Utilizzare una libreria come Jackson o GSON di deserializzare il JSON per le istanze di classi.

Se si desidera un approccio più dinamico, i suddetti framework possono anche essere serializzati su mappe.

1

come Bozho detto creare la struttura di classe che reflacts JSON e quindi utilizzare libreria jacson come segue:

riferiscono 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

È possibile utilizzare una libreria come JSON-java

import org.json.JSONObject; 

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

sì, si puoi usare jacson per analizzarlo ma c'è un modo più semplice per farlo suo lib di Jsonme "import org.json.me" non devi annuncio d file jar usarlo

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

Sì, è più facile, ma se il progetto è complesso consiglio che l'uso jacson lib

0

È possibile utilizzare:

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