gpt4 book ai didi

json - 仅将 Spring MVC 中提到的字段序列化为 JSON 响应

转载 作者:行者123 更新时间:2023-12-04 21:57:07 26 4
gpt4 key购买 nike

我正在使用 spring 编写休息服务MVC 这会产生 JSON 响应。它应该允许客户端仅选择给定的字段作为响应,这意味着客户端可以将他感兴趣的字段作为 url 参数提及,例如 ?fields=field1,field2 .

使用 Jackson 注释并不能提供我正在寻找的东西,因为它不是动态的,而且 Jackson 中的过滤器似乎也没有足够的希望。
到目前为止,我正在考虑实现一个可以解决这个问题的自定义消息转换器。

有没有其他更好的方法来实现这一目标?我想如果这个逻辑不与我的服务或 Controller 耦合。

最佳答案

从 Spring 4.2 开始,@JsonFilter MappingJacksonValue 支持

  • 问题:SPR-12586 : Support Jackson @JsonFilter
  • 提交:ca06582

  • 您可以直接将 PropertyFilter 注入(inject) Controller 中的 MappingJacksonValue。
    @RestController
    public class BookController {
    private static final String INCLUSION_FILTER = "inclusion";

    @RequestMapping("/novels")
    public MappingJacksonValue novel(String[] include) {
    @JsonFilter(INCLUSION_FILTER)
    class Novel extends Book {}

    Novel novel = new Novel();
    novel.setId(3);
    novel.setTitle("Last summer");
    novel.setAuthor("M.K");

    MappingJacksonValue res = new MappingJacksonValue(novel);
    PropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept(include);
    FilterProvider provider = new SimpleFilterProvider().addFilter(INCLUSION_FILTER, filter);
    res.setFilters(provider);
    return res;
    }

    或者您可以通过 ResponseBodyAdvice 声明全局策略。以下示例通过“排除”参数实现过滤策略。
    @ControllerAdvice
    public class DynamicJsonResponseAdvice extends AbstractMappingJacksonResponseBodyAdvice {
    public static final String EXCLUDE_FILTER_ID = "dynamicExclude";
    private static final String WEB_PARAM_NAME = "exclude";
    private static final String DELI = ",";
    private static final String[] EMPTY = new String[]{};

    @Override
    protected void beforeBodyWriteInternal(MappingJacksonValue container, MediaType contentType,
    MethodParameter returnType, ServerHttpRequest req, ServerHttpResponse res) {
    if (container.getFilters() != null ) {
    // It will be better to merge FilterProvider
    // If 'SimpleFilterProvider.addAll(FilterProvider)' is provided in Jackson, it will be easier.
    // But it isn't supported yet.
    return;
    }

    HttpServletRequest baseReq = ((ServletServerHttpRequest) req).getServletRequest();
    String exclusion = baseReq.getParameter(WEB_PARAM_NAME);

    String[] attrs = StringUtils.split(exclusion, DELI);
    container.setFilters(configFilters(attrs));
    }

    private FilterProvider configFilters(String[] attrs) {
    String[] ignored = (attrs == null) ? EMPTY : attrs;
    PropertyFilter filter = SimpleBeanPropertyFilter.serializeAllExcept(ignored);
    return new SimpleFilterProvider().addFilter(EXCLUDE_FILTER_ID, filter);
    }
    }

    关于json - 仅将 Spring MVC 中提到的字段序列化为 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26014943/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com