【问题标题】:How can I iterate JSONObject to get individual items如何迭代 JSONObject 以获取单个项目
【发布时间】:2012-10-13 05:41:26
【问题描述】:

这是我下面的代码,我需要从中解析JSONObject 以获取单个项目。这是我第一次使用 JSON。所以不确定如何解析JSONObject 以从JSONObject 获取单个项目。

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

我的 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
            }
        }
    }
}

我需要从上述对象中获取latitudelongitudecitystatecountrypostal_code。任何人都可以提供任何建议如何有效地做到这一点?

【问题讨论】:

    标签: java json


    【解决方案1】:

    你可以试试这个,它会递归地找到一个 json 对象中的所有键值并构造为一个 map 。您可以简单地从 Map 中获取您想要的键。

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

    输出:

        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}
    

    【讨论】:

    • 好答案。我只想提一下,在这种情况下,Map&lt;String, String&gt; 工作得很好,但为了使其更通用,我会使用Map&lt;String, Object&gt;,因为有些字段是数字的。
    【解决方案2】:

    这个怎么样?

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

    本示例代码使用"org.json.JSONObject"

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 2021-10-20
      相关资源
      最近更新 更多