从JsonArray获取值并将其存储在数组中

时间:2020-09-08 04:49:50

标签: java arrays json

我正在尝试从以下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"));
}

1 个答案:

答案 0 :(得分:0)

  1. JSON数组看起来像这样[1,2,3,4],而不是{1,2,3,4}

这可以为您提供帮助。

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