你可以尝试这样的事情:
String str = "{CDG: {\n"
+ "id: \"32569\",\n"
+ "airport_name: \"Charles De Gaulle\",\n"
+ "latitude: \"49.0167\",\n"
+ "longitude: \"2.55\",\n"
+ "timezone: \"2\",\n"
+ "dst_indicator: \"E\",\n"
+ "city: \"Paris\",\n"
+ "country: \"France\",\n"
+ "country_code: \"FR\",\n"
+ "region: \"TC1\",\n"
+ "listing_display: \"true\",\n"
+ "pseudonyms: \"\"\n"
+ "},\n"
+ "ORY: {\n"
+ "id: \"33539\",\n"
+ "airport_name: \"Orly\",\n"
+ "latitude: \"48.7167\",\n"
+ "longitude: \"2.3833\",\n"
+ "timezone: \"2\",\n"
+ "dst_indicator: \"E\",\n"
+ "city: \"Paris\",\n"
+ "country: \"France\",\n"
+ "country_code: \"FR\",\n"
+ "region: \"TC1\",\n"
+ "listing_display: \"true\",\n"
+ "pseudonyms: \"\"\n"
+ "},\n"
+ "LBG: {\n"
+ "id: \"123425\",\n"
+ "airport_name: \"Le Bourget\",\n"
+ "latitude: \"48.969444\",\n"
+ "longitude: \"2.441389\",\n"
+ "timezone: \"1\",\n"
+ "dst_indicator: \"E\",\n"
+ "city: \"Paris\",\n"
+ "country: \"France\",\n"
+ "country_code: \"FR\",\n"
+ "region: \"TC1\",\n"
+ "listing_display: \"true\",\n"
+ "pseudonyms: \"\"\n"
+ "}}";
使用 gson,您可以按如下方式检索键名:
Gson gson = new Gson();
Object o = gson.fromJson(str, Object.class);
List keys = new ArrayList();
Collection values = null;
if (o instanceof Map) {
Map map = (Map) o;
keys.addAll(map.keySet()); // collect keys at current level in hierarchy
values = map.values();
} else if (o instanceof Collection) {
values = (Collection) o;
}
System.out.println(keys);// [CDG, ORY, LBG]
for (int i = 0; i < keys.size(); i++) {
System.out.println(keys.get(i));
}
并使用java-json您可以执行以下操作:
JSONObject jsonObject = new JSONObject(str);
String[] names = jsonObject.getNames(jsonObject);
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);// all names are printed here : LBG,ORY, etc
// then parsing the names accordingly..
JSONObject jsonObject1 = jsonObject.getJSONObject(names[i]);
System.out.println(jsonObject1.getString("city"));
}
从 url 获取 json:
public static String connectionGet(String url, String parameter) throws MalformedURLException, ProtocolException, IOException {
URL url1 = new URL(url);
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.setRequestMethod("GET");
request1.connect();
String responseBody = convertStreamToString(request1.getInputStream());
return responseBody;
}
String str = connectionGet("http://www.cleartrip.com/common/json/airports.json", "");