0

May i know how to get JSON object from an json array??

JSON:

[
    {
        "id": 1,
        "user": {
            "id": 20710,
            "username": "abc",
            "first_name": "",
            "last_name": "",
        },
        "action": {
            "name": "xxx",
            "date": 19/01/01,
        },
    },
    {
        "id": 2,
        "user": {
            "username": "xyx",
            "first_name": "xxx",
            "last_name": "yyy",
        },
        "action": {
            "name": "xxx",
            "date": 19/05/01,
        },

    },]

I want to get username of these users in a list, but i cant get the value when i get this json from api as JSONArray.

My code:

public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                    Log.d("Create Response", response.toString());

                    ArrayList<String> list = new ArrayList<String>();
                    JSONArray jsonArray = response;
                    try {
                    if (jsonArray != null) {
                        int len = jsonArray.length();
                        for (int i=0;i<len;i++){
                            JSONObject c=response.getJSONObject(1);
                            String id = c.getString(i);

                            HashMap<String, String> map = new HashMap<String, String>();

                            map.put("id", id);
                                feeds_List.add(map);
                        }
                    }

I cannot use

JSONObject object=JsonArray.getJSONObject("user");

here,

it only accept int for getJSONObject("user"); if it is JSONArray

2
  • Have you managed to parse the JSON into an JSON array? If yes, what is your next problem, if no, why not? Commented Apr 27, 2015 at 7:36
  • @Smutje i can get the json into json array, but then i don't know how to get the json object "inside" it , 1)i can get values like id , but cannot get object like "user" and "action" since it is nested. Commented Apr 27, 2015 at 7:43

1 Answer 1

4

You can use like this also.Suppose response String is userInfo

ArrayList<String> usernames = new ArrayList<String>();
JSONArray userList = new JSONArray(userInfo);
for (int j = 0; j < userList.length(); j++) {
  JSONObject userObject = new JSONObject(userList.getString(j));
  String user = userObject.getString("user");
  JSONObject usernameInfo = new JSONObject(user);
  usernames.add(usernameInfo.getString("username"));

}

Try this, if not working please mention me in comment.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.