1

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!

4

4 回答 4

4

那是因为username存在于data对象中,而对象恰好是JSONArray. data响应对象中获取数组,遍历JSONObject数组中的每个对象,然后从每个对象中提取您的username.

像这样的东西: -

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"));
}
于 2013-04-19T09:25:40.263 回答
2

你需要先得到JSONArray哪个是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");
}

你可以从这里得到关于解析 JSON 的想法

于 2013-04-19T09:29:15.403 回答
2

您的字段用户名在数组数据中。要访问此尝试:

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");
}
于 2013-04-19T09:27:33.730 回答
1

尝试这个...

尝试 {

        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());
    }
于 2013-04-19T09:32:13.303 回答