我有一個對象圖,我想返回不同的視圖。我不想用Jackson的@JsonViews
來實現這一點。現在,我使用Jackson MixIn類來配置顯示哪些字段。然而,我所有的休息方法返回一個字符串,而不是像BusinessCategory
或Collection<BusinessCategory>
類型。我無法找到一種方法來根據我想要的數據動態配置Jackson序列化程序。 Spring中是否有任何功能配置哪個Jackson序列化器在每個功能的基礎上使用?我發現文章提到存儲哪些字段需要在線程本地序列化,並有一個過濾器發送它們和另一個基於Spring @Role
的後期過濾,但沒有涉及在每個函數基礎上選擇序列化器(或MixIn)。有任何想法嗎?有沒有辦法自定義Spring MVC使用的ObjectMapper而不返回String?
我認爲提議的解決方案的關鍵是如果返回類型是一個對象,而不是字符串。
下面是我的圖中的對象。
public class BusinessCategory implements Comparable<BusinessCategory> {
private String name;
private Set<BusinessCategory> parentCategories = new TreeSet<>();
private Set<BusinessCategory> childCategories = new TreeSet<>();
// getters, setters, compareTo, et cetera
}
我跨線從Spring MVC控制器作爲JSON像這樣在發送這些:
@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));
}
}
我有一個混合其中又加入ObjectMapper使用模塊配置的序列化。
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);
}
}
我目前的解決方案的作品,它只是不覺得很乾淨。
"categories" : [ {
"name" : "Personal Driver",
"parentCategories" : [ {
"name" : "Transportation",
"parentCategories" : [ ]
} ]
}
哦,是的,我使用的是:
- 春季啓動1.2.7
- 彈簧框架:4.1.8
- 傑克遜在這裏列出2.6.3
- 其他:http://docs.spring.io/spring-boot/docs/1.2.7.RELEASE/reference/html/appendix-dependency-versions.html
你不想使用'@ JsonViews',因爲你想保持映射器配置綁定到'@ RequestMapping'方法,對吧? – approxiblue
是的,我希望JSON映射配置本地化爲@RequestMapping方法(和關聯的映射助手)。我*不想*僅僅想要序列化的數據創建一組新對象。 –