0

I have question about parsing a specific json string. I didn't find anything which helps me in my situation. I have this 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
}

So the thing that I want to know is there a way to get the value of that JSONObject : AM , BM. They are different everytime so I can't check for them, but I want to be able to save them as String. Here is what I'm using actually to parse that 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();
    }
}

So any suggestions how can I get these values?

Android-Droid
  • 14,365
  • 41
  • 114
  • 185

1 Answers1

6

I don't know if I understand you correctly. You want to have "AM" and "BM" as String value, so that you have the short tag for the country name.

The "AM" is the key you're iterating over: keys.next()

String short = String.valueOf(keys.next());
JSONObject country = json.getJSONObject(short);
flo
  • 1,988
  • 12
  • 15