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?
The @Controller annotation indicates that a particular class serves the role of a controller. There is no need to extend any controller base class or reference the Servlet API. You are of course still able to reference Servlet-specific features if you need to.
The @Controller annotation indicates that a particular class serves the role of a controller. Spring Controller annotation is typically used in combination with annotated handler methods based on the @RequestMapping annotation. It can be applied to classes only. It's used to mark a class as a web request handler.
Jackson mixins is a mechanism to add Jackson annotations to classes without modifying the actual class. It was created for those cases where we can't modify a class such as when working with third-party classes. We can use any Jackson annotation but we don't add them directly to the class.
I ended up following what this guy did:
https://github.com/martypitt/JsonViewExample
and created my own project here:
https://github.com/jackmatt2/JsonResponse
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With