【问题标题】:Spring and Jackson Json: serialising two different sets of fieldsSpring和Jackson Json:序列化两组不同的字段
【发布时间】:2011-09-28 03:49:15
【问题描述】:

我有一个 Classified 接口,使用带有 Visibility.NONE 的 @JsonAutoDetect 进行注释,因此我可以选择单个 getter 并使用 @JsonSerialize 注释进行序列化

@JsonAutoDetect(getterVisibility = Visibility.NONE)
public interface Classified {

    @JsonSerialize
    String getModel();

直到这里没有问题,当我从我的@Controller返回带有@ResponseBody注释的Classified时,它可以返回预期的JSON:

    @RequestMapping(value = "/classified/{idClassified}", method = RequestMethod.GET)
    @ResponseBody
    public final Classified getClassified(@PathVariable final int idClassified) {

但是,当我返回分类列表时,我想返回一组较小的 getter,而使用以下签名,显然它会返回所有标记的 getter:

@RequestMapping(value = "/classified", method = RequestMethod.GET)
@ResponseBody
public final List<Classified> searchClassified(@RequestParam final int idBrand,
    @RequestParam final String priceMax, @RequestParam final int page) {

我不知道如何在列表的每个项目中返回分类 getter 的较小子集。

【问题讨论】:

    标签: java spring spring-mvc jackson


    【解决方案1】:

    查看“filtering properties”,其中列出了更改序列化内容的多种方法。我猜想 Json Views 可能是最简单的一个。可以使用一个较小的视图,然后在没有定义视图时默认“全部”模式(默认是序列化所有属性)。

    【讨论】:

    • 其实我今天又回到了这个问题。 Json Views 是一个有趣的概念,但是 objectMapper 是由 Spring 调用的,所以我不知道如何告诉渲染特定的视图,after reading here
    • 其实我posted another question 是关于如何使用这些视图的。阅读文档后,我不知道如何使用它们。你真的在 Spring 中使用过它们吗?谢谢
    • 不,我主要使用 JAX-RS (Jersey),所以对 Spring MVC 只有二手知识
    【解决方案2】:

    “返回一组较小的 getter”

    如果您的意思是减少列表中的项目数,请更改控制器的 searchClassified 方法中的业务逻辑。

    如果您的意思是减少每个项目上可用的公共 getter 方法的数量,您可以创建一个仅实现原始项目 getter 子集的接口,并返回它们的列表。

    【讨论】:

    • 是的,很抱歉不清楚,我的意思是第二个“减少每个项目上可用的公共 getter 方法的数量”。我今天试试,谢谢!
    • 我喜欢你的解决方案,简单明了,而我仍在尝试理解另一个,我已经发布了一个关于它的新问题。我有一个答案,但我仍然无法弄清楚。麻烦的是,不幸的是,这个解决方案不起作用,即使我返回 ClassifiedPublic 接口的列表,在 JSON 中有所有属性,包括私有属性,可能是因为 Spring 通过反射找到它们。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 2017-05-30
    • 2012-07-04
    • 2019-10-21
    • 1970-01-01
    • 2011-06-28
    相关资源
    最近更新 更多