有没有办法自定义Spring MVC使用的ObjectMapper而不返回String?

时间:2015-10-27 20:14:02

标签: spring-mvc jackson

我有一个对象图表,我想返回不同的视图。我不想使用杰克逊的@JsonViews来实现这一点。现在,我使用Jackson MixIn类来配置显示哪些字段。但是,我的所有rest方法都返回一个String而不是像BusinessCategoryCollection< BusinessCategory >这样的类型。我想不出根据我想要的数据动态配置Jackson序列化器的方法。 Spring中是否有任何功能可以配置每个功能使用哪个Jackson序列化程序?我发现帖子提到存储你想要在线程本地序列化的哪些字段,并有一个过滤器发送它们和另一个基于Spring @Role的后置过滤,但没有解决选择序列化器(或MixIn)的问题功能基础。有什么想法吗?

我认为提出的解决方案很好的关键是返回类型是一个对象,而不是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));
  }
}

我在MixIn中配置了序列化,然后使用模块将其添加到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 个答案:

答案 0 :(得分:0)

最后,满足我需求的唯一过程是创建一组仅暴露我想要公开的字段的视图对象。在宏观方案中,它只为项目添加了少量看似不必要的代码,使数据流更容易理解。