1

我正在使用 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 调用,他将不会获得属性,如果他使用 3 调用,他将不会获得属性。

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

4

1 回答 1

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 中注册这种转换,我认为这篇文章会对您有所帮助

于 2012-08-21T17:29:10.610 回答