您可以尝试这样做,它将在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}


