从具有空值的 API 获取数据

问题描述 投票:0回答:1

因此,当我尝试从数组中获取 JsonObject 时,我收到一条错误,指出它应该从第 1 行开始:
`ERROR 34879 --- [gbac] [nio-8080-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] 在路径 [] 的上下文中抛出异常 [请求处理失败:org.json.JSONException:JSONObject 文本必须以 '{' at 1 [character 2 line 1]] 开头,根本原因

org.json.JSONException:JSONObject 文本必须以 '{' at 1 [character 2 line 1] 开头 `

但是当我将其切换到 JSONArray 以返回 JSON 对象时,它在测试时返回一个空数组。

[]

这是 JSON API 格式:

[
  {
    "id": "298f43b988d512301f1283f58465be55",
    "sport_key": "basketball_nba",
    "sport_title": "NBA",
    "commence_time": "2024-04-16T23:40:00Z",
    "completed": false,
    "home_team": "New Orleans Pelicans",
    "away_team": "Los Angeles Lakers",
    "scores": null,
    "last_update": null
  },
  {
    "id": "c0b61bf137d5bf5aafe6ade79b6800a1",
    "sport_key": "basketball_nba",
    "sport_title": "NBA",
    "commence_time": "2024-04-17T02:00:00Z",
    "completed": false,
    "home_team": "Sacramento Kings",
    "away_team": "Golden State Warriors",
    "scores": null,
    "last_update": null
  },
  {
    "id": "f13eb486120d8466fc3d004f69280112",
    "sport_key": "basketball_nba",
    "sport_title": "NBA",
    "commence_time": "2024-04-17T23:10:00Z",
    "completed": false,
    "home_team": "Philadelphia 76ers",
    "away_team": "Miami Heat",
    "scores": null,
    "last_update": null
  }
]

以下是将 API 中的分数解析为 JSONobject 或 JSONArray 的代码:

public List<Score> parseScore(JSONArray jsonArray) {
        List<Score> scores = new ArrayList<>();
        try {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String sportId = jsonObject.getString("id");
                // Check if scores is null or not
                if (!jsonObject.isNull("scores")) {
                    JSONArray scoreArray = jsonObject.getJSONArray("scores");
                    for (int j = 0; j < scoreArray.length(); j++) {
                        JSONObject scoreObj = scoreArray.getJSONObject(j);
                        String scoreValue = scoreObj.optString("score", "n/a");
                        String name = scoreObj.optString("name", "n/a");
                        if (scoreValue != null && name != null) {
                            Score scoreModel = new Score();
                            scoreModel.setSport_Id(sportId);
                            scoreModel.setScore(scoreValue);
                            scoreModel.setName(name);
                            scores.add(scoreModel);
                        } else {
                            // Log a warning or handle the missing data appropriately
                            System.out.println("Invalid or missing score data in JSON object.");
                        }
                    }
                }
            }
        } catch (JSONException e) {
            // Log or handle JSON parsing error
            e.printStackTrace();
        }
        return scores;
    }

获取NBAScores方法:

@GetMapping("/scores/nba")
    public ResponseEntity<List<Score>> getNBAScores() {
        // Parse the mocked response
        List<Score> nbaScores = oddsAPIAdapter.parseScore(new JSONArray(oddsAPIAdapter.mockedScoreResponse));

        // Save scores to the database (assuming sportRepository.save(score) is correctly implemented)

        // Return the NBA scores
        return new ResponseEntity<>(nbaScores, HttpStatus.OK);
    }

我是 API 新手,正在使用 springboot/postman 进行开发,我很感谢您提出的反馈或建设性批评。

我希望它能够获得每场 NBA 比赛的得分,即使比赛尚未开始。另外,这个 API 调用很旧,我只是用它来节省我的免费 API 密钥。 这个项目可以做得更好,但我时间紧迫。

spring-boot api postman
1个回答
0
投票

以下是如何修改代码来处理这些情况:

public List<Score> parseScore(JSONArray jsonArray) {
List<Score> scores = new ArrayList<>();
try {
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        String sportId = jsonObject.getString("id");
        // Check if scores is null or not
        if (!jsonObject.isNull("scores")) {
            Object scoresObj = jsonObject.get("scores");
            if (scoresObj instanceof JSONArray) {
                JSONArray scoreArray = (JSONArray) scoresObj;
                for (int j = 0; j < scoreArray.length(); j++) {
                    JSONObject scoreObj = scoreArray.getJSONObject(j);
                    String scoreValue = scoreObj.optString("score", "n/a");
                    String name = scoreObj.optString("name", "n/a");
                    if (scoreValue != null && name != null) {
                        Score scoreModel = new Score();
                        scoreModel.setSport_Id(sportId);
                        scoreModel.setScore(scoreValue);
                        scoreModel.setName(name);
                        scores.add(scoreModel);
                    } else {
                        // Log a warning or handle the missing data appropriately
                        System.out.println("Invalid or missing score data in JSON object.");
                    }
                }
            } else {
                // Handle the case when "scores" is not an array
                System.out.println("Invalid format for scores in JSON object.");
            }
        } else {
            // Handle the case when "scores" is null
            System.out.println("Scores are null for the JSON object.");
        }
    }
} catch (JSONException e) {
    // Log or handle JSON parsing error
    e.printStackTrace();
}
return scores;

}

© www.soinside.com 2019 - 2024. All rights reserved.