user3234804 user3234804 - 9 days ago 7
Android Question

Convert json to string in java

How I can put a complicated json object in an array of strings?

JSON sample

{
"FriendsList": [
{
"username": "ChanServ",
"avatar": "http:\/\/clavatars.photos-box.org\/chack.jpg"
},
{
"username": "kroot",
"avatar": "http:\/\/clavatars.photos-box.org\/land2.jpg"
},
{
"username": "morrildl",
"avatar": "http:\/\/clavatars.photos-box.org\/land3.jpg"
},
{
"username": "addo",
"avatar": "http:\/\/clavatars.photos-box.org\/land8.jpg"
}
]
}


and this is the code:

protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONObject json;
try {
json = new JSONObject(result);
tvhttp.setText(json.toString(2));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Answer

Try this one

JSONObject json = null;
    try {
        json = new JSONObject(result);
        JSONArray jsonArray = json.getJSONArray("FriendsList");

        for (int j = 0; j < jsonArray.length(); j++) {

            JSONObject jsonObjectData1 = jsonArray.getJSONObject(j);

            String username = jsonObjectData1.getString("username");
            String avatar = jsonObjectData1.getString("avatar");
        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }