我正在尝试编写一个json
解析器字符串,它可以解析任何json输入,无论它是否嵌套。给予该函数的任何json
输入都可以打印json
传递的所有键值对。
我尝试过类似下面的内容。我知道这不是正确的方法,但有人可以帮助我解决这个问题。我正在使用json.simple
。如果可以通过json.simple
,请提供帮助。
public static void parseJson(String json){
try {
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(json);
JSONObject jsonChildObject = (JSONObject)obj.get("results");
Iterator iterator = jsonChildObject.keySet().iterator();
String key = null;
while(iterator.hasNext()){
key = (String)iterator.next();
System.out.println(((JSONObject)jsonChildObject.get(key)));
}
} catch (ParseException e) {
e.printStackTrace();
}
}
JSON:
{ "results" : [ { "address_components" : [ { "long_name" : "1600", "short_name" : "1600", "types" : [ "street_number" ] }, { "long_name" : "Amphitheatre Parkway", "short_name" : "Amphitheatre Pkwy", "types" : [ "route" ] }, { "long_name" : "Mountain View", "short_name" : "Mountain View", "types" : [ "locality", "political" ] }, { "long_name" : "Santa Clara County", "short_name" : "Santa Clara County", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "California", "short_name" : "CA", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : [ "country", "political" ] }, { "long_name" : "94043", "short_name" : "94043", "types" : [ "postal_code" ] } ], "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA", "geometry" : { "location" : { "lat" : 37.4223895, "lng" : -122.0843123 }, "location_type" : "ROOFTOP", "viewport" : { "northeast" : { "lat" : 37.4237384802915, "lng" : -122.0829633197085 }, "southwest" : { "lat" : 37.42104051970851, "lng" : -122.0856612802915 } } }, "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA", "types" : [ "street_address" ] } ], "status" : "OK"}