0

在这里,我想从 json 中获取数据,但我只得到前两个对象值 (25, 44) 但 id 是 50,60 。我不知道这段代码有什么问题。

以下是我来自服务器的回复:

{
"product": {
    "25": {
        "training": "First Name",
        "taken": null,
        "date": "1386737285",
        "body":"http://abc.xyz.in/video1.mp4",
        "image": "http://abc.xyz.in/video1.jpg"
    },
    "44": {
        "training": "Second Name",
        "taken": null,
        "date": "1389951618",
        "body":"http://abc.xyz.in/video2.mp4",
        "image":"http://abc.xyz.in/video2.jpg"
    },
    "50": {
        "training": "Third Name",
        "taken": null,
        "date": "1389971004",
        "body":"http://abc.xyz.in/video3.mp4",
        "image": "http://abc.xyz.in/video3.jpg"
    },
    "60": {
        "training": "Fourth Name",
        "taken": null,
        "date": "1390003200",
        "body": "http://abc.xyz.in/video4.mp4",
        "image": "http://abc.xyz.in/video4.jpg"
    }
  }
}

下面是从 json 中获取数据的代码:

 public String[] getDataFromResponse(String jsonProfileResponse,String secondParam,
        String attributeName ) {

    String[] attributeValue = null;
    try {
        json = new JSONTokener(jsonProfileResponse).nextValue();
        if (json instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) json;
            JSONObject jObj = jsonObject.getJSONObject(secondParam);
            System.out.println(jObj);
            Iterator<?> keys = jObj.keys();
            List<String> listitems = new ArrayList<String>();
            List<String> nids = new ArrayList<String>();
            while (keys.hasNext()) {
                nids.add(String.valueOf(keys.next()));
                JSONObject jsonObj = jObj.getJSONObject(String.valueOf(keys
                        .next()));
                System.out.println(jsonObj);
                listitems.add(jsonObj.getString(attributeName));
            }
            attributeValue = listitems.toArray(new String[0]);
                trainingId = nids.toArray(new String[0]);
        }

    } catch (JSONException ex) {
        ex.printStackTrace();
    }
    return attributeValue;

}

谢谢考虑...

4

3 回答 3

3

在 hasNext 中,您调用了两次 keys.next()

所以,而不是

  nids.add(String.valueOf(keys.next()));
  JSONObject jsonObj = jObj.getJSONObject(String.valueOf(keys.next()));

你所要做的

  String currentKey = String.valueOf(keys.next());
  nids.add(currentKey);
  JSONObject jsonObj = jObj.getJSONObject(currentKey);
于 2014-01-28T08:15:14.710 回答
1
String key="";
while (keys.hasNext()) {
   key= keys.next()
   JSONObject jsonObj = jObj.getJSONObject(String.valueOf(key));
   nids.add(key));
   System.out.println(jsonObj);
   listitems.add(jsonObj.getString(attributeName));
}

使用 key.next() 两次是问题

于 2014-01-28T08:15:45.793 回答
0

因为在 JSONObject 中,键的顺序是未定义的。

@see:http: //developer.android.com/reference/org/json/JSONObject.html#keys%28%29

尝试在服务器上对数据进行排序,然后在 JSONArray 中响应

于 2014-01-28T08:43:25.807 回答