我对解析特定的json
字符串有疑问。在我的情况下,我找不到任何可以帮助我的东西。我有这个json:
{
"AM": {
"country_name": "Armenia",
"data": {
"180854": {
"time_published": "2012-03-30 13:31:39",
"title": "Example",
},
"180926": {
"time_published": "2012-04-02 05:21:44",
"title": "Example",
}, // keeps going on
}
},
"BM": {
"country_name": "Bolivia",
"data": {
"180854": {
"time_published": "2012-03-30 13:31:39",
"title": "Example",
},
"180926": {
"time_published": "2012-04-02 05:21:44",
"title": "Industrial PPI inflation eases to 5.5% y/y in February",
}
}
}, // continues
}
所以我想知道的是有办法获得JSONObject
:AM
,BM
的价值。它们每次都不同,所以我无法检查它们,但我希望能够将它们保存为String
。以下是我实际用来解析JSON的内容:
public static void jsonParser(String jsonBuffer){
try {
//String jsonData = new String(jsonBuffer,"UTF-8");
JSONObject json = (JSONObject) new JSONTokener(jsonBuffer).nextValue();
//JSONObject country = json.getJSONObject(String.valueOf(json.keys().next()));
Log.d("","json : "+json);
Iterator<Object> keys = json.keys();
while (keys.hasNext()) {
JSONObject country = json.getJSONObject(String.valueOf(keys.next()));
String countryName = country.getString("country_name");
Log.e("","country_name: "+countryName);
JSONObject data = country.getJSONObject("data");
Iterator<Object> keys2 = data.keys();
while(keys2.hasNext()){
JSONObject datas = data.getJSONObject(String.valueOf(keys2.next()));
String published = datas.getString("time_published");
Log.d("","published : "+published);
String title = datas.getString("title");
Log.w("","title : "+title);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
所以有什么建议我如何获得这些价值?
答案 0 :(得分:6)
我不知道我是否理解正确。您希望将“AM”和“BM”作为字符串值,以便您拥有国家/地区名称的短标记。
“AM”是您正在迭代的关键:keys.next()
String short = String.valueOf(keys.next());
JSONObject country = json.getJSONObject(short);