I have a graph of objects that I would like to return different views to. I do not want to use Jackson @JsonViews
to implement this. I am currently using the Jackson MixIn classes to customize the fields. However, all my rest methods return a string, not a type of type BusinessCategory
or Collection< BusinessCategory >
. I cannot determine how to dynamically tune the Jackson serializer based on what kind I would like to get from the data. Is there any function built into Spring to configure which Jackson serializer to use for each function? I found messages that mentioned which fields you want to serialize in a thread-local and have a filter, send them and another Spring-based message filtering @Role
, but nothing addresses the choice of serializer (or MixIn) functional basis. Any ideas?
The key to thinking about the proposed solution is good if the type of the returned object is an object, not a string.
Here are the objects on my chart.
public class BusinessCategory implements Comparable<BusinessCategory> {
private String name;
private Set<BusinessCategory> parentCategories = new TreeSet<>();
private Set<BusinessCategory> childCategories = new TreeSet<>();
}
I send them by cable from Spring MVC as JSON, for example:
@RestController
@RequestMapping("/business")
public class BusinessMVC {
private Jackson2ObjectMapperBuilder mapperBuilder;
private ObjectMapper parentOnlyMapper;
@Autowired
public BusinessMVCfinal(Jackson2ObjectMapperBuilder mapperBuilder) {
this.mapperBuilder = mapperBuilder;
this.parentOnlyMapper = mapperBuilder.build();
parentOnlyMapper.registerModule(new BusinessCategoryParentsOnlyMapperModule());
}
@RequestMapping(value="/business_category/parents/{categoryName}")
@ResponseBody
public String getParentCategories(@PathVariable String categoryName) throws JsonProcessingException {
return parentOnlyMapper.writeValueAsString(
BusinessCategory.businessCategoryForName(categoryName));
}
}
I set up serialization in MixIn, which in turn was added to ObjectMapper using a module.
public interface BusinessCategoryParentsOnlyMixIn {
@JsonProperty("name") String getName();
@JsonProperty("parentCategories") Set<BusinessCategory> getParentCategories();
@JsonIgnore Set<BusinessCategory> getChildCategories();
}
public class BusinessCategoryParentsOnlyMapperModule extends SimpleModule {
public BusinessCategoryParentsOnlyMapperModule() {
super("BusinessCategoryParentsOnlyMapperModule",
new Version(1, 0, 0, "SNAPSHOT", "", ""));
}
public void setupModule(SetupContext context) {
context.setMixInAnnotations(
BusinessCategory.class,
BusinessCategoryParentsOnlyMixIn.class);
}
}
My current solution is working, it is just not very clean.
"categories" : [ {
"name" : "Personal Driver",
"parentCategories" : [ {
"name" : "Transportation",
"parentCategories" : [ ]
} ]
}
Oh yes, I use: