gpt4 book ai didi

java - Android 中的 JSON 对象

转载 作者:行者123 更新时间:2023-12-01 18:37:19 24 4
gpt4 key购买 nike

这里我想从 json 中获取数据,但我只获取前两个对象值 (25, 44) 但 ids 是 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;

}

感谢您的考虑...

最佳答案

在 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);

关于java - Android 中的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21400067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com