gpt4 book ai didi

java - 根据 Spring Controller 方法配置 JSON 输出

转载 作者:太空宇宙 更新时间:2023-11-04 07:04:32 25 4
gpt4 key购买 nike

目前我正在使用 Jackson JSON Processor 从对象返回 JSON,但如果有更好的方法来做到这一点,我愿意接受建议。目标是根据方法/url 定义 JSON 响应中将包含哪些属性。

示例:

型号

class League {
String name;
List<Team> teams;
...
}

class Team {
String name;
String nation;
int points;
List<Player> players;
...
}

class Player {
String name;
Team team;
...
}

Controller

@Controller
public class LeagueController {

@RequestMapping(value="/league",method = RequestMethod.GET)
public @ResponseBody
League getLeague() {
//return the teams shouldn't include the player list
}

@RequestMapping(value="/team/{id}",method = RequestMethod.GET)
public @ResponseBody
Team getTeamById(Long id) {
//return team including the players but if possibe use the teamname inside the JSON
//instead of the entire back reference (which producess an infinite loop.
}
}

我查看了 Jackson 注释,但它没有让我进一步了解或提出新问题。

最佳答案

您可以使用 JSON 自定义注释来忽略字段、忽略 null 、忽略 java 类 中的 empty StringJSON 转换,

@JsonIgnore
private KeyValueCollection userData;

private String participants = "";

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
private boolean garbageEligible;


@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
private String interactionType ;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
private LinkedList<InteractionInfo> interactions;

我使用了jackson 1.9

希望这有帮助。

关于java - 根据 Spring Controller 方法配置 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21610734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com