使用json mixin和spring 4控制器的更好方法

时间:2014-01-02 22:35:07

标签: json spring spring-mvc jackson

是否有更好的方法(可能使用注释)将mixin添加到弹簧控制器。

目前我这样做:

@RequestMapping(value = "/accounts",
        produces = MediaType.APPLICATION_JSON_VALUE,
        method = RequestMethod.GET,
        params = "q")
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
public final String getAccountsViaQuery(@RequestParam("q") final String query) 
        throws JsonGenerationException, JsonMappingException, IOException {

    final List<Account> matchingAccounts = accountService.findByAccountNameOrNumber(query);
    ObjectMapper mapper = new ObjectMapper();
    SerializationConfig serializationConfig = mapper.getSerializationConfig();
    serializationConfig.addMixInAnnotations(Account.class, Account.SearchJsonMixin.class);

    return mapper.writeValueAsString(matchingAccounts);
}

我宁愿这样做

@RequestMapping(value = "/accounts",
        produces = MediaType.APPLICATION_JSON_VALUE,
        method = RequestMethod.GET,
        params = "q")
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
public final List<Account> getAccountsViaQuery(@RequestParam("q") final String query) 
        throws JsonGenerationException, JsonMappingException, IOException {
    return accountService.findByAccountNameOrNumber(query);
}

对我来说看起来好多了,没有样板代码,返回类型是编译器检查的。

是否可以在我的控制器上使用某种注释来添加json mixin?

1 个答案:

答案 0 :(得分:1)

写了一个注释来解决这个问题。

https://github.com/jackmatt2/JsonResponse