You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring 2.7.2中反序列化NHL API嵌套JSON获取指定字段

简便反序列化实现方案

针对你的需求,这里提供两种无需编写全量POJO的简便方案,适配Spring 2.7.2环境:

方案1:使用Jackson JsonPath直接提取字段

无需定义任何POJO,直接通过JsonPath表达式从响应中提取目标字段,适合快速实现。

步骤:

  1. 确保项目中包含Jackson相关依赖(Spring Boot默认已集成),若需更简洁的JsonPath语法,可额外引入com.jayway.jsonpath:json-path依赖。
  2. 通过RestTemplate获取API响应的字符串或JsonNode,再用JsonPath解析提取字段。

示例代码:

@RestController
public class NhlScheduleController {
    private final RestTemplate restTemplate;

    public NhlScheduleController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/nhl-schedule")
    public List<Map<String, String>> getNhlSchedule() {
        String apiUrl = "https://statsapi.web.nhl.com/api/v1/schedule?teamId=55&startDate=2022-10-01&endDate=2023-04-21";
        String jsonResponse = restTemplate.getForObject(apiUrl, String.class);

        List<Map<String, Object>> dateEntries = JsonPath.read(jsonResponse, "$.dates[*]");
        List<Map<String, String>> scheduleResult = new ArrayList<>();

        for (Map<String, Object> dateEntry : dateEntries) {
            String gameDate = (String) dateEntry.get("date");
            List<Map<String, Object>> games = (List<Map<String, Object>>) dateEntry.get("games");

            for (Map<String, Object> game : games) {
                Map<String, Object> teams = (Map<String, Object>) game.get("teams");
                Map<String, Object> homeTeam = (Map<String, Object>) teams.get("home");
                Map<String, Object> awayTeam = (Map<String, Object>) teams.get("away");

                String homeTeamName = (String) ((Map<String, Object>) homeTeam.get("team")).get("name");
                String awayTeamName = (String) ((Map<String, Object>) awayTeam.get("team")).get("name");

                Map<String, String> gameInfo = new HashMap<>();
                gameInfo.put("date", gameDate);
                gameInfo.put("主队", homeTeamName);
                gameInfo.put("客队", awayTeamName);
                scheduleResult.add(gameInfo);
            }
        }
        return scheduleResult;
    }
}

方案2:定义极简POJO(忽略多余字段)

仅创建需要的嵌套POJO类,通过@JsonIgnoreProperties(ignoreUnknown = true)忽略所有不需要的字段,既保证类型安全,又避免编写冗余代码。

步骤:

  1. 逐层定义只包含目标字段的POJO,每个类添加@JsonIgnoreProperties(ignoreUnknown = true)注解。
  2. 用RestTemplate直接将API响应反序列化为顶层POJO,再提取目标字段。

示例代码:

极简POJO类:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
public class ScheduleResponse {
    private List<DateEntry> dates;

    // Getter
    public List<DateEntry> getDates() {
        return dates;
    }

    public void setDates(List<DateEntry> dates) {
        this.dates = dates;
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)
class DateEntry {
    private String date;
    private List<Game> games;

    // Getters
    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public List<Game> getGames() {
        return games;
    }

    public void setGames(List<Game> games) {
        this.games = games;
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Game {
    private Teams teams;

    // Getter
    public Teams getTeams() {
        return teams;
    }

    public void setTeams(Teams teams) {
        this.teams = teams;
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Teams {
    private Team home;
    private Team away;

    // Getters
    public Team getHome() {
        return home;
    }

    public void setHome(Team home) {
        this.home = home;
    }

    public Team getAway() {
        return away;
    }

    public void setAway(Team away) {
        this.away = away;
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Team {
    private String name;

    // Getter
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Controller代码:

@RestController
public class NhlScheduleController {
    private final RestTemplate restTemplate;

    public NhlScheduleController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/nhl-schedule")
    public List<Map<String, String>> getNhlSchedule() {
        String apiUrl = "https://statsapi.web.nhl.com/api/v1/schedule?teamId=55&startDate=2022-10-01&endDate=2023-04-21";
        ScheduleResponse response = restTemplate.getForObject(apiUrl, ScheduleResponse.class);

        List<Map<String, String>> scheduleResult = new ArrayList<>();
        for (DateEntry dateEntry : response.getDates()) {
            String gameDate = dateEntry.getDate();
            for (Game game : dateEntry.getGames()) {
                String homeTeamName = game.getTeams().getHome().getName();
                String awayTeamName = game.getTeams().getAway().getName();

                Map<String, String> gameInfo = new HashMap<>();
                gameInfo.put("date", gameDate);
                gameInfo.put("主队", homeTeamName);
                gameInfo.put("客队", awayTeamName);
                scheduleResult.add(gameInfo);
            }
        }
        return scheduleResult;
    }
}

方案对比

  • JsonPath方案:无需编写POJO,代码量少,适合快速验证或临时需求;缺点是缺乏类型检查,字段路径变更时易出错。
  • 极简POJO方案:类型安全,代码可读性和维护性更好,适合长期使用的业务场景;缺点需要编写少量嵌套类,但工作量远小于全量POJO。

内容的提问来源于stack exchange,提问作者h8t4nk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 18:57:17