7

I am using spring with jackson for json responses.

I want to create an annotation to allow a feature of jackson called mixins. The idea is similar to this question 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();
}

Usage:

@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);
}

Normally (without the annotations) it would be done as follows:

@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);
}

Using this custom annotation how would I link into the internal object mapper and tell it to use the mixins supplied by the annotations?

Community
  • 1
  • 1
jax
  • 37,735
  • 57
  • 182
  • 278

1 Answers1

9

I ended up following what this guy did:

https://github.com/martypitt/JsonViewExample

and created my own project here:

https://github.com/jackmatt2/JsonResponse

jax
  • 37,735
  • 57
  • 182
  • 278