Marko Niciforovic
Marko Niciforovic

Reputation: 3591

Problems with getting values from JSON object

I'm trying to get data once user logged in successfully but I never get any of results, what I am doing is next:

// response is my request to server
JSONObject obj = new JSONObject(response);
Log.d("RESPONSE",obj.toString());

so in log I do see values, like:

04-19 11:28:16.729: D/RESPONSE(3162): {"data":[{"loses":3,"username":"benedict","level":1,"strength":15,"experience":null,"gold":10,"password":"benedict","intelligence":5,"agility":10,"wins":5}],"status":true}

but once I try to read username for example like this:

String username = obj.getString("username");

The code above ^ gives me nothing in my string.. Any help how I can retrieve data from JSONObject? Thanks!

Upvotes: 1

Views: 1861

Answers (4)

Android
Android

Reputation: 106

Try this...

try {

        JSONObject object = new JSONObject(response);
        JSONArray Jarray = object.getJSONArray("data");

        for (int i = 0; i < Jarray.length(); i++) {

           JSONObject Jasonobject = Jarray.getJSONObject(i);
           String loose= Jasonobject.getString("loses");
           String username=Jasonobject.getString("username");
          ....... 
          ........



        }

    } catch (JSONException e) {

        Log.e("log_txt", "Error parsing data " + e.toString());
    }

Upvotes: 1

Hardik Joshi
Hardik Joshi

Reputation: 9507

You need to first get JSONArray which is data :

    JSONArray data = null;
        data = json.getJSONArray("data");
         for(int i = 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);
         String username = c.getString("username");
}

You can get idea about parsing JSON from HERE

Upvotes: 2

throrin19
throrin19

Reputation: 18197

your field username is in array data. To access into this try :

JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("data");

for(int i = 0; i < array.length(); ++i){
    JSONObject data = array.getJSONObject(i);
    String username = data.getString("username");
}

Upvotes: 2

Rahul
Rahul

Reputation: 45060

That is because the username is present in the data object, which happens to be an JSONArray. Get the data array from the response object, traverse through each JSONObject in the array, and from each object, extract your username.

Something like this:-

JSONObject obj = new JSONObject(response);
JSONArray data = obj.getJSONArray("data");
for(int i=0;i<data.length();i++){
    JSONObject eachData = data.getJSONObject(i);
    System.out.println("Username= "+ eachData.getString("username"));
}

Upvotes: 4

Related Questions