1

I am using Spring MVC Annotations to create a JSON Rest API that has methods defined like:

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

For dealing with different client Versions I want to exclude or include properties of the serialized beans by using an Annotation like

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

    @InterfaceVersion(min = 3)
    String new;
}

So if the client calls with InterfaceVersion 2 he will not get the new property and if he calls with 3 he will not get the old property.

I already found the the Jackson library (which is used by Spring for JSON) provides Features like JsonView, JsonFilter and so on but I could not figure out where and how I have to configure these things.

Thomas Einwaller
  • 8,873
  • 4
  • 40
  • 55

1 Answers1

1

I use @JsonFilter to selectively filter out properties on the same object, Spring didn't (and still doesn't?) support this at the time, so I registered a custom MappingJackson2HttpMessageConverter which inspects the return type, and if it is a filter wrapper type, I take the filter out and apply it.

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);
    }
}

}

I use java @config instead of xml configuration as much as I can, so I do:

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

I think this post will help you if you want to register this kind of conversion in xml

Community
  • 1
  • 1
bytesandwich
  • 373
  • 2
  • 10