为spring控制器创建一个@JsonMixin注释

时间:2014-01-07 10:00:03

标签: spring-mvc jackson

我正在使用带杰克逊的春天来回应json。

我想创建一个注释,以允许jackson的一个名为mixins的功能。这个想法类似于这个问题Using Jackson Mixins with MappingJacksonHttpMessageConverter & Spring MVC

public @interface JsonMixin{
  public class target();
  public class mixin();
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface JsonFilter{
    public JsonMixin[] mixins();
}

用法:

@JsonFilter(mixins={
  @JsonMixin(target=Target1.class, mixin=Mixin1.class),
  @JsonMixin(target=Target2, mixin=Mixin2.class)
})
@RequestMapping(value = "/accounts/{id}",
        produces = MediaType.APPLICATION_JSON_VALUE,
        method = RequestMethod.GET)
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
public final Account getAccountsViaQuery(@PathParam("id") final long id) 
        throws IOException {
    return accountService.get(id);
}

通常(没有注释)它将按如下方式完成:

@RequestMapping(value = "/accounts/{id}",
        produces = MediaType.APPLICATION_JSON_VALUE,
        method = RequestMethod.GET)
@ResponseBody
@ResponseStatus(value = HttpStatus.OK)
public final Account getAccountsViaQuery(@PathParam("id") final long id) 
        throws IOException {
final String matchingAccounts = accountService.findByAccountNameOrNumber(query);
    ObjectMapper mapper = new ObjectMapper();
    SerializationConfig serializationConfig = mapper.getSerializationConfig();
    serializationConfig.addMixInAnnotations(Target1.class, Mixin1.class);
    serializationConfig.addMixInAnnotations(Target2.class, Mixin2.class);

    return mapper.writeValueAsString(matchingAccounts);
}

使用这个自定义注释我如何链接到内部对象映射器并告诉它使用注释提供的mixins?

1 个答案:

答案 0 :(得分:9)

我最后关注了这个人做了什么:

https://github.com/martypitt/JsonViewExample

在这里创建了我自己的项目:

https://github.com/jackmatt2/JsonResponse