2012-10-13 12 views
20

Dies ist mein Code unten, aus dem ich die JSONObject analysieren muss, um einzelne Elemente zu erhalten. Dies ist das erste Mal, dass ich mit JSON arbeite. Also nicht sicher, wie man JSONObject parsen kann, um die einzelnen Artikel von JSONObject zu erhalten.Wie kann ich JSONObject iterieren, um einzelne Elemente zu erhalten

try { 
    String url = service + version + method + ipAddress + format; 
    StringBuilder builder = new StringBuilder(); 
    httpclient = new DefaultHttpClient(); 
    httpget = new HttpGet(url); 
    httpget.getRequestLine(); 
    response = httpclient.execute(httpget); 
    HttpEntity entity = response.getEntity(); 
    if (entity != null) { 
     InputStream inputStream = entity.getContent(); 
     bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
     for (String line = null; (line = bufferedReader.readLine()) != null;) { 
      builder.append(line).append("\n"); 
     } 
     JSONObject jsonObject = new JSONObject(builder.toString()); 
     // Now iterate jsonObject to get Latitude,Longitude,City,Country etc etc. 

    } 

} catch (Exception e) { 
    getLogger().log(LogLevel.ERROR, e.getMessage()); 
} finally { 
    bufferedReader.close(); 
    httpclient.getConnectionManager().shutdown(); 
} 

Meine JSON sieht wie folgt aus:

{ 
    "ipinfo": { 
     "ip_address": "131.208.128.15", 
     "ip_type": "Mapped", 
     "Location": { 
      "continent": "north america", 
      "latitude": 30.1, 
      "longitude": -81.714, 
      "CountryData": { 
       "country": "united states", 
       "country_code": "us" 
      }, 
      "region": "southeast", 
      "StateData": { 
       "state": "florida", 
       "state_code": "fl" 
      }, 
      "CityData": { 
       "city": "fleming island", 
       "postal_code": "32003", 
       "time_zone": -5 
      } 
     } 
    } 
} 

Ich brauche latitude, zu bekommen longitude, city, state, country, postal_code aus dem obigen Objekt. Kann jemand einen Vorschlag machen, wie man es effizient macht?

Antwort

60

du versuchen können, es wird rekursiv alle Schlüsselwerte in einem JSON-Objekt und Konstrukte als eine Karte. Sie können einfach den gewünschten Schlüssel von der Karte erhalten.

public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{ 
    Iterator<String> keys = json.keys(); 
    while(keys.hasNext()){ 
     String key = keys.next(); 
     String val = null; 
     try{ 
      JSONObject value = json.getJSONObject(key); 
      parse(value,out); 
     }catch(Exception e){ 
      val = json.getString(key); 
     } 

     if(val != null){ 
      out.put(key,val); 
     } 
    } 
    return out; 
} 

public static void main(String[] args) throws JSONException { 

    String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}"; 

    JSONObject object = new JSONObject(json); 

    JSONObject info = object.getJSONObject("ipinfo"); 

    Map<String,String> out = new HashMap<String, String>(); 

    parse(info,out); 

    String latitude = out.get("latitude"); 
    String longitude = out.get("longitude"); 
    String city = out.get("city"); 
    String state = out.get("state"); 
    String country = out.get("country"); 
    String postal = out.get("postal_code"); 

    System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal); 

    System.out.println("ALL VALUE " + out); 

} 

Ausgang:

Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003 
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1} 
+5

Gute Antwort. Ich würde nur erwähnen, dass in diesem Fall "Map " gut funktioniert, aber um es allgemeiner zu machen, würde ich 'Map ' machen, da einige der Felder numerisch sind. – Tavo

12

Wie wäre es damit?

JSONObject jsonObject = new JSONObject   (YOUR_JSON_STRING); 
JSONObject ipinfo  = jsonObject.getJSONObject ("ipinfo"); 
String  ip_address = ipinfo.getString   ("ip_address"); 
JSONObject location = ipinfo.getJSONObject  ("Location"); 
String  latitude = location.getString  ("latitude"); 
System.out.println (latitude); 

Dieser Beispielcode verwendet "org.json.JSONObject"

Verwandte Themen