Mauricio Silva
Mauricio Silva

Reputation: 483

Get a String from an Array in JSON in Android Studio

I have a problem. I want to access a String ("name") from a JSONObject that has 3 arrays and I'm trying to access a particular one of those 3.

This is the bigger Array.

{"id":[{"id":"2","name":"Yuliem"}],"success":1,"message":"Product successfully created."}

I want to access the one that's named id, and then access the data in "name".

TAG_CODE = hospitalSelectedId;
        hspCode = hospitalSelectedId;
        TAG_IMEI = imei;

        //Build the parameters
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("code", TAG_CODE));
        params.add(new BasicNameValuePair("imei", TAG_IMEI));
        params.add(new BasicNameValuePair("long", String.valueOf(lon)));
        params.add(new BasicNameValuePair("lat", String.valueOf(lat)));
        params.add(new BasicNameValuePair("alt", String.valueOf(alt)));

        //Getting JSON Object
        JSONObject json = jsonParser.makeHttpRequest(url_login, "POST", params);

        //Check logcat for response
        Log.d("Create Response", json.toString());

        try {
            success = json.getInt(TAG_SUCCESS);
            //userId = ;
            Log.d("User's id: ", String.valueOf(json.get("id")));

            if (success == 1) {
                // finish closes the current Activity
                // finish();

                Intent goHome = new Intent(LoginActivity.this, HomepageActivity.class);
                startActivity(goHome);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

The previous code gives me

[{"id":"2","name":"Yuliem"}]

But I have no clue how to access "name". Help please :)

Upvotes: 2

Views: 2538

Answers (1)

varren
varren

Reputation: 14731

If you want to get "Yuliem" you can do this:

String json = "{\"id\":[{\"id\":\"2\",\"name\":\"Yuliem\"}],\"success\":1,\"message\":\"Product successfully created.\"}";
JSONObject obj = new JSONObject(json);
JSONArray array = (JSONArray) obj.get("id");
JSONObject innerObj = (JSONObject) array.get(0);
Log.d("User's name: ",innerObj.get("name"));

Upvotes: 2

Related Questions