2011-11-22 16 views
32
{ 
    "Response": { 
     "MetaInfo": { 
      "Timestamp": "2011-11-21T14:55:06.556Z" 
     }, 
     "View": [ 
      { 
       "_type": "SearchResultsViewType", 
       "ViewId": 0, 
       "Result": [ 
        { 
         "Relevance": 0.56, 
         "MatchQuality": { 
          "Country": 1, 
          "State": 1, 
          "County": 1, 
          "City": 1, 
          "PostalCode": 1 
         }, 
         "Location": { 
          "LocationType": "point", 
          "DisplayPosition": { 
           "Latitude": 50.1105, 
           "Longitude": 8.684 
          }, 
          "MapView": { 
           "_type": "GeoBoundingBoxType", 
           "TopLeft": { 
            "Latitude": 50.1194932, 
            "Longitude": 8.6699768 
           }, 
           "BottomRight": { 
            "Latitude": 50.1015068, 
            "Longitude": 8.6980232 
           } 
          }, 
          "Address": { 
           "Country": "DEU", 
           "State": "Hessen", 
           "County": "Frankfurt am Main", 
           "City": "Frankfurt am Main", 
           "District": "Frankfurt am Main", 
           "PostalCode": "60311", 
           "AdditionalData": [ 
            { 
             "value": "Germany", 
             "key": "CountryName" 
            } 
           ] 
          } 
         } 
        } 
       ] 
      } 
     ] 
    } 
} 

Sto cercando di recuperare il codice postale dal JSON precedente. Sto usando Gson per analizzarlo. Sono molto nuovo a JSON e da quello che ho letto da tutti i post qui (alcuni molto simili a questo), ho capito che il nome dei campi dovrebbe essere così com'è. Quindi capisco che devo fare 4 classi: risposta, vista, risultato e indirizzo. Ho creato classi statiche nidificate, ma ottengo solo un valore nullo come output. Nel prossimo JSON, ho più indirizzi. Ma sono bloccato su questa singola risposta.Analizza un JSON nidificato utilizzando gson

Per un breve esempio, cerco di recuperare timestamp con questo codice, ma mi dà un valore nullo

public class ParseJSON { 
    public static void main(String[] args) throws Exception { 
     BufferedReader br = new BufferedReader(new FileReader("try.json")); 

     Gson gson = new GsonBuilder().create(); 
     Pojo pojo = gson.fromJson(br,Pojo.class); 
     System.out.println(Pojo.Response.MetaInfo.Timestamp); 
     br.close(); 
    } 
} 

class Pojo { 
    public Pojo() { } 

    static class Response{ 
     static class MetaInfo { 
      static public String Timestamp; 

      public String getTimestamp() { 
        return Timestamp; 
      } 
     } 
    } 
} 
+0

sto lottando con questo, se qualcuno mi può aiutare sarò grato. – RFT

risposta

42

Se avete solo bisogno il "PostalCode", è possibile utilizzare JsonParser invece di avere un gruppo di classi :

JsonParser jsonParser = new JsonParser(); 
JsonObject address = jsonParser.parse(json) 
    .getAsJsonObject().get("Response") 
    .getAsJsonObject().getAsJsonArray("View").get(0) 
    .getAsJsonObject().getAsJsonArray("Result").get(0) 
    .getAsJsonObject().get("Location") 
    .getAsJsonObject().getAsJsonObject("Address"); 
String postalCode = address.get("PostalCode").getAsString(); 

o per tutti i risultati:

JsonArray results = jsonParser.parse(json) 
     .getAsJsonObject().get("Response") 
     .getAsJsonObject().getAsJsonArray("View").get(0) 
     .getAsJsonObject().getAsJsonArray("Result"); 
for (JsonElement result : results) { 
    JsonObject address = result.getAsJsonObject().get("Location").getAsJsonObject().getAsJsonObject("Address"); 
    String postalCode = address.get("PostalCode").getAsString(); 
    System.out.println(postalCode); 
} 
+0

Grazie ha funzionato. Inoltre, ero curioso, questo dovrebbe funzionare anche per più indirizzi, giusto? – RFT

+0

@sid: fantastico. Intendi più risultati? Si può scorrere su 'getAsJsonArray (" Result ")' questo è ciò che intendi. – jeha

+0

sì, ho elementi che sono array contenenti indirizzi e ho bisogno del codice postale da tutti gli indirizzi. Non ho capito cosa intendi ripetendo su getAsJsonArray ("Risultato"). – RFT

10

Per rendere il vostro esempio lavoro Timestamp, provo:

public class ParseJSON { 
    public static void main(String[] args) throws Exception { 
     BufferedReader br = new BufferedReader(new FileReader("try.json")); 

     Gson gson = new GsonBuilder().create(); 
     Pojo pojo = gson.fromJson(br, Pojo.class); 

     System.out.println(pojo.Response.MetaInfo.Timestamp); 
     br.close(); 
    } 
} 

class Pojo { 
    Response Response = new Response(); 
} 

class Response { 
    MetaInfo MetaInfo = new MetaInfo(); 
} 

class MetaInfo { 
    String Timestamp; 
} 
+0

Ho provato una cosa simile prima, visualizza ancora null! – RFT

+1

@sid: hai fatto 'Pojo ...' non 'pojo ...' - per favore prova questo - funziona per me e dovrebbe anche per te – jeha

+1

Questa è la risposta più appropriata alla domanda rispetto all'altra. –

Problemi correlati