I’m using OpenAPI to define my api and resources and the classes are auto-generated. I’ve been looking for a way to have a single model and multiple representations so am looking at JsonViews or Filters.
Is there any way to add JsonViews to the properties of the generated model classes ? I haven’t been able to figure it out.
Advertisement
Answer
I’ve found a way to arrive to the intended behaviour without modifying the generated classes.
The steps are :
create a subclass of the generated class
add the additional properties that are to be internal fields into the subclass
configure the ObjectMapper to MapperFeature.DEFAULT_VIEW_INCLUSION = true, which means that any properties without the JsonView model will be included in Serialization (the defualt is false)
add JsonView to the subclass properties
@JsonView(Views.Private.class)
and different JsonView at the controller endpoints
@JsonView(Views.Public.class)
With the above in place the controller endpoints will Serialise only the fields of the generated model, since they do not have the JsonView, and the fields with the JsonView on the subclass will remin internal to the application.
Code snippet of the ObjectMapper config :
@Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true); return mapper; }