【问题标题】:Filtering Properties from Jackson JSON从 Jackson JSON 过滤属性
【发布时间】:2012-06-20 22:45:07
【问题描述】:

我正在使用 Spring MVC Annotations 创建一个 JSON Rest API,其方法定义如下:

@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public @ResponseBody AuthenticationResponse authenticate(@RequestBody final DeviceInformation deviceInformation)
            throws AuthenticationException {
    return createAuthenticationResponse(deviceInformation, false);
}

为了处理不同的客户端版本,我想通过使用类似注释来排除或包含序列化 bean 的属性

class AuthenticationResponse {
    @InterfaceVersion(max = 2) 
    String old;

    @InterfaceVersion(min = 3)
    String new;
}

因此,如果客户端使用 InterfaceVersion 2 调用,他将不会获得 new 属性,如果他使用 3 调用,他将不会获得 old 属性。

我已经发现 Jackson 库(Spring 用于 JSON)提供了 JsonView、JsonFilter 等功能,但我不知道我必须在哪里以及如何配置这些东西。

【问题讨论】:

    标签: json spring-mvc jackson


    【解决方案1】:

    我使用@JsonFilter 有选择地过滤掉同一对象上的属性,当时 Spring 不(现在仍然不?)支持这一点,所以我注册了一个自定义 MappingJackson2HttpMessageConverter 来检查返回类型,如果它是一种过滤器包装类型,我将过滤器取出并应用它。

    public class JsonFilterAwareMappingJackson2HttpMessageConverter extends
        MappingJackson2HttpMessageConverter {
    
    private boolean prefixJson = false;
    
    @Override
    public void setPrefixJson(boolean prefixJson) {
        this.prefixJson = prefixJson;
        super.setPrefixJson(prefixJson);
    }
    
    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
    
        JavaType javaType = getJavaType(clazz);
        try {
            return this.getObjectMapper().readValue(inputMessage.getBody(), javaType);
        }
        catch (IOException ex) {
            logger.error("Could not read JSON: " + ex.getMessage());
            throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
        }
    
    }
    
    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {
        JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
        ObjectMapper objectMapper = getObjectMapper();
        JsonGenerator jsonGenerator =
                objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);
    
        // A workaround for JsonGenerators not applying serialization features
        // https://github.com/FasterXML/jackson-databind/issues/12
        if (objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
            jsonGenerator.useDefaultPrettyPrinter();
        }
    
        try {
            if (this.prefixJson) {
                jsonGenerator.writeRaw("{} && ");
            }
    
            objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            if (object instanceof FilterAppliedJsonObject) {
                FilterAppliedJsonObject viewObject = FilterAppliedJsonObject.class.cast(object);
                objectMapper.setFilters(viewObject.getFilters());
                objectMapper.writeValue(jsonGenerator, viewObject.getObject()); 
            } else if (object == null) {
                jsonGenerator.writeNull();
    
            } else {
                objectMapper.writeValue(jsonGenerator, object); 
            }
        }
        catch (JsonProcessingException ex) {
            logger.error("Could not write JSON: " + ex.getMessage());
            throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
        }
    }
    
    }
    

    我尽可能多地使用 java @config 而不是 xml 配置,所以我这样做了:

    @Override
    public void configureMessageConverters(
            List<HttpMessageConverter<?>> converters) {
        converters.add(new JsonFilterAwareMappingJackson2HttpMessageConverter());
        super.configureMessageConverters(converters);
    }
    

    如果您想在xml中注册这种转换,我认为this post会帮助您

    【讨论】:

      猜你喜欢
      • 2015-08-04
      • 2013-09-16
      • 2014-10-23
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 2013-03-24
      • 2021-06-11
      • 2012-08-31
      相关资源
      最近更新 更多