0

我对解析特定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
}

所以我想知道的是有没有办法获得它的价值JSONObjectAMBM。它们每次都不同,所以我无法检查它们,但我希望能够将它们保存为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();
    }
}

那么有什么建议我怎样才能得到这些值?

4

1 回答 1

6

我不知道我对你的理解是否正确。您希望将“AM”和“BM”作为字符串值,以便您拥有国家名称的短标签。

“AM”是您要迭代的键:keys.next()

String short = String.valueOf(keys.next());
JSONObject country = json.getJSONObject(short);
于 2012-04-14T13:51:08.153 回答