根据Spring Controller方法配置JSON输出

时间:2014-02-06 18:12:08

标签: java json spring rest jackson

目前我正在使用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.
  }
}

我查看了杰克逊的注释,但它没有让我更进一步或提出新的问题。

1 个答案:

答案 0 :(得分:1)

您可以使用JSON自定义注释来忽略字段,忽略null,忽略empty Stringjava class转换中的JSON,< / p>

@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

希望这有帮助。