我正在尝试从以下ArrayofJson集中提取“得分”
我只想在数组中获得1,2,1,3分。像int sample [] = {1,1,1,1,1,1,1,1,1}; 我们该怎么办?
import org.json.JSONArray;
import org.json.JSONObject;
public static void main(String args[]) {
JSONArray jsonArray = new JSONArray(
"[{\"Qnum\":1124,\"Response\":\"London\\n\",\"SelectedResponse\":\"1\",\"Score\":1.0},{\"Qnum\":1125,\"Response\":\"Sydney\\n\",\"SelectedResponse\":\"2\",\"Score\":2.0},{\"Qnum\":1126,\"Response\":\"Paris\\n\",\"SelectedResponse\":\"1\",\"Score\":1.0},{\"Qnum\":1183,\"Response\":\"NewYork\\n\",\"SelectedResponse\":\"3\",\"Score\":3.0}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
Iterator<String> keys = json.keys();
System.out.println(json.getDouble("Score"));
}
答案 0 :(得分:0)
这可以为您提供帮助。
// If You Wanted to have JSONArray
List<Double> scores = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
double score = json.getDouble("Score");
scores.add(score);
}
JSONArray array = new JSONArray(scores);
System.out.println(array);
// If You Wanted to have Java Array of double
double []scoresDouble = new double[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
double score = json.getDouble("Score");
scoresDouble[i] = score;
}
System.out.println(Arrays.toString(scoresDouble));
// If You Wanted to have Java Array of int (as mentioned on the questing)
int []scoresInt = new int[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
double score = json.getDouble("Score");
scoresInt[i] = (int) score;
}
System.out.println(Arrays.toString(scoresInt));