我有上面的JSON代码,作为回复:
"candidates": [
{
"subtest1": "0.802138030529022",
"enrollment_timestamp": "1416850761"
},
{
"elizabeth": "0.802138030529022",
"enrollment_timestamp": "1417207485"
},
{
"elizabeth": "0.777253568172455",
"enrollment_timestamp": "1416518415"
},
{
"elizabeth": "0.777253568172455",
"enrollment_timestamp": "1416431816"
}
]
我尝试从candidates
数组中获取名称。
public void dataCheck(String text){
System.out.println("JSON response:");
System.out.println(text);
try {
JSONObject jsonRootObject = new JSONObject(text);
JSONArray jsonArray = jsonRootObject.optJSONArray("candidates");
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String subtest1 = jsonObject.optString("subtest1").toString();
}
} catch (JSONException e){
e.printStackTrace();
}
}
很难,因为这些值是数组的数组而没有标识符。标识符是确切的值,因此无法在我的代码中定义变量。我只需要第一个值,例如本例中的subtest1
。
答案 0 :(得分:1)
// Get the keys in the first JSON object
Iterator<?> keys = jsonObject.keys();
if (keys.hasNext()) {
// Get the key
String key = (String)keys.next();
String objValue = jsonObject.getString(key);
...
}