栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

我如何迭代JSONObject以获得单个项目

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

我如何迭代JSONObject以获得单个项目

您可以尝试这样做,它将在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_pre': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_pre': 'fl'},'CityData': {'city': 'fleming island','postal_pre': '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_pre");    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 32003ALL VALUE {region=southeast, ip_type=Mapped, state_pre=fl, state=florida, country_pre=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_pre=32003, continent=north america, longitude=-81.714, latitude=30.1}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/469286.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号