【问题标题】:Configure JSON Output depending on Spring Controller Method根据 Spring Controller 方法配置 JSON 输出
【发布时间】:2014-02-06 18:12:08
【问题描述】:

目前我正在使用 Jackson JSON 处理器从对象返回 JSON,但如果有更好的方法,我愿意提供建议。目标是定义哪些属性将包含在 JSON 响应中,具体取决于方法/url。

例子:

型号

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
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 注释,但它没有让我进一步了解或提出新问题。

【问题讨论】:

  • 我认为您正在寻找的是 Jackson 自定义序列化程序。
  • 请检查我的答案,让我知道以寻求帮助。

标签: java json spring rest jackson


【解决方案1】:

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

@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

希望这会有所帮助。

【讨论】:

  • 感谢您的回复,我会在接下来的几天内尝试并回来标记您的答案或有其他问题。
  • 欢迎。那么请告诉我你发生了什么事?
猜你喜欢
  • 1970-01-01
  • 2012-02-27
  • 2021-08-21
  • 2017-07-29
  • 2012-05-25
  • 2012-06-01
  • 1970-01-01
  • 2010-10-12
  • 2021-09-30
相关资源
最近更新 更多