使用Jackson Mixins和MappingJacksonHttpMessageConverter& Spring MVC

时间:2012-08-07 20:47:26

标签: java json spring-mvc jackson

我马上就会回答我真正的问题/问题,有没有办法在HttpMessageConverter 中访问控制器处理程序方法的注释?我很确定答案是否定的(在浏览Spring的源代码之后)。

使用Jackson Mixins时是否还有其他方法可以使用MappingJacksonHttpMessageConverter配对?我已经基于MappingJacksonHttpMessageConverter实现了我自己的HttpMessageConverter来“升级”它以使用Jackson 2.0。

Controller.class

@Controller
public class Controller {

    @JsonFilter({ @JsonMixin(target=MyTargetObject.class, mixin=MyTargetMixin.class) })
    @RequestMapping(value="/my-rest/{id}/my-obj", method=RequestMethod.GET, produces="application/json")
    public @ResponseBody List<MyTargetObject> getListOfFoo(@PathVariable("id") Integer id) {
        return MyServiceImpl.getInstance().getBarObj(id).getFoos();
    }
}

@JsonFilter是我希望传递给mapper的自定义注释,然后可以自动将其直接提供给ObjectMapper。

MappingJacksonHttpMessageConverter.class

public class MappingJacksonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

    ...

    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) {

            //Obviously, no access to the HandlerMethod here.

    }

    ...
}

我为这个答案进行了广泛的搜索。到目前为止,我只看到人们在Controller的处理方法中将其对象序列化为JSON(在每种方法中反复违反DRY principle)。或直接注释其数据对象(没有关于如何公开对象的解耦或多种配置)。

可能无法在HttpMessageConverter中完成。还有其他选择吗?拦截器可以访问HandlerMethod,但不能访问处理程序方法的返回对象。

3 个答案:

答案 0 :(得分:3)

这不是理想的解决方案。请参阅我的第二个答案。

我使用ModelAndViewResolver解决了这个问题。您可以直接向AnnotationMethodHandlerAdapter注册这些内容,并且知道在默认处理发生之前它们将始终首先启动。因此,Spring的文档 -

/**
 * Set a custom ModelAndViewResolvers to use for special method return types.
 * <p>Such a custom ModelAndViewResolver will kick in first, having a chance to resolve
 * a return value before the standard ModelAndView handling kicks in.
 */
public void setCustomModelAndViewResolver(ModelAndViewResolver customModelAndViewResolver) {
    this.customModelAndViewResolvers = new ModelAndViewResolver[] {customModelAndViewResolver};
}

查看ModelAndViewResolver接口,我知道它包含了将一些功能扩展到处理程序方法的工作方式所需的所有参数。

public interface ModelAndViewResolver {

    ModelAndView UNRESOLVED = new ModelAndView();

    ModelAndView resolveModelAndView(Method handlerMethod,
            Class handlerType,
            Object returnValue,
            ExtendedModelMap implicitModel,
            NativeWebRequest webRequest);
}

resolveModelAndView中查看所有这些美味的论点!我几乎可以访问Spring知道的所有请求。以下是我实现界面与MappingJacksonHttpMessageConverter非常相似的方式,除了以单向方式(向外):

public class JsonModelAndViewResolver implements ModelAndViewResolver {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    public static final MediaType DEFAULT_MEDIA_TYPE = new MediaType("application", "json", DEFAULT_CHARSET);

    private boolean prefixJson = false;

    public void setPrefixJson(boolean prefixJson) {
        this.prefixJson = prefixJson;
    }

    /**
     * Converts Json.mixins() to a Map<Class, Class>
     *
     * @param jsonFilter Json annotation
     * @return Map of Target -> Mixin classes
     */
    protected Map<Class<?>, Class<?>> getMixins(Json jsonFilter) {

        Map<Class<?>, Class<?>> mixins = new HashMap<Class<?>, Class<?>>();

        if(jsonFilter != null) {
            for(JsonMixin jsonMixin : jsonFilter.mixins()) {
                mixins.put(jsonMixin.target(), jsonMixin.mixin());
            }
        }

        return mixins;
    }

    @Override
    public ModelAndView resolveModelAndView(Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest) {

        if(handlerMethod.getAnnotation(Json.class) != null) {

            try {

                HttpServletResponse httpResponse = webRequest.getNativeResponse(HttpServletResponse.class);

                httpResponse.setContentType(DEFAULT_MEDIA_TYPE.toString());

                OutputStream out = httpResponse.getOutputStream();

                ObjectMapper objectMapper = new ObjectMapper();

                objectMapper.setMixInAnnotations(getMixins(handlerMethod.getAnnotation(Json.class)));

                JsonGenerator jsonGenerator =
                        objectMapper.getJsonFactory().createJsonGenerator(out, JsonEncoding.UTF8);

                if (this.prefixJson) {
                    jsonGenerator.writeRaw("{} && ");
                }

                objectMapper.writeValue(jsonGenerator, returnValue);

                out.flush();
                out.close();

                return null;

            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return UNRESOLVED;
    }

}

上面使用的唯一自定义类是我的注释类@Json,其中包含一个名为mixins的参数。以下是我在Controller端实现这一点的方法。

@Controller
public class Controller {

    @Json({ @JsonMixin(target=MyTargetObject.class, mixin=MyTargetMixin.class) })
    @RequestMapping(value="/my-rest/{id}/my-obj", method=RequestMethod.GET)
    public @ResponseBody List<MyTargetObject> getListOfFoo(@PathVariable("id") Integer id) {
        return MyServiceImpl.getInstance().getBarObj(id).getFoos();
    }
}

这是一个非常棒的简单。 ModelAndViewResolver会自动将返回对象转换为JSON并应用带注释的混合。

由于新的3.0标记不允许直接配置ModelAndViewResolver,因此必须恢复到Spring 2.5配置方式的“向下”(如果你称之为)。也许他们只是忽略了这个?

我的旧配置(使用Spring 3.1风格)

<mvc:annotation-driven />

我的新配置(使用Spring 2.5风格

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
    <property name="customModelAndViewResolvers">
        <list>
            <bean class="my.package.mvc.JsonModelAndViewResolver" />
        </list>
    </property>
</bean>

^^ 3.0+没有办法连接自定义ModelAndViewResolver。因此,切换回旧式。

这是自定义注释:

<强>的Json

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Json {

    /**
     * A list of Jackson Mixins.
     * <p>
     * {@link http://wiki.fasterxml.com/JacksonMixInAnnotations}
     */
    JsonMixin[] mixins() default {};

}

<强> JsonMixin

public @interface JsonMixin {
    public Class<? extends Serializable> target();
    public Class<?> mixin();
}

答案 1 :(得分:2)

在发布下面的答案之后,我改变了我的做法。我使用了HandlerMethodReturnValueHandle r。我不得不创建一个程序化的Web配置来覆盖订单,因为最后触发了自定义返回值处理程序。我需要在默认值之前触发它们。

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
   ...
}

希望这会导致某人的方向比我下面的答案更好。

这允许我将任何对象直接序列化为JSON。在@RequestMapping中有produce =“application / json”,那么我总是将返回值序列化为JSON。

我为参数绑定做了同样的事情,除了我使用HandlerMethodArgumentResolver。只需使用您选择的注释注释您的类(我使用了JPA @Entity,因为我通常会将其序列化为模型)。

您现在可以在Spring控制器中使用无缝POJO到JSON de / serialization,而无需任何样板代码。

Bonus:我有的参数解析器将检查参数的@Id标签,如果JSON包含Id的密钥,则检索实体并将JSON应用于持久化对象。的Bam

/**
 * De-serializes JSON to a Java Object.
 * <p>
 * Also provides handling of simple data type validation.  If a {@link JsonMappingException} is thrown then it
 * is wrapped as a {@link ValidationException} and handled by the MVC/validation framework.
 *
 * @author John Strickler
 * @since 2012-08-28
 */
public class EntityArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private SessionFactory sessionFactory;

    private final ObjectMapper objectMapper = new ObjectMapper();

    private static final Logger log = Logger.getLogger(EntityArgumentResolver.class);

    //whether to log the incoming JSON
    private boolean doLog = false;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().getAnnotation(Entity.class) != null;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String requestBody = IOUtils.toString(request.getReader());
        Class<?> targetClass = parameter.getParameterType();
        Object entity = this.parse(requestBody, targetClass);
        Object entityId = getId(entity);

        if(doLog) {
            log.info(requestBody);
        }

        if(entityId != null) {
            return copyObjectToPersistedEntity(entity, getKeyValueMap(requestBody), entityId);
        } else {
            return entity;
        }
    }


    /**
     * @param rawJson a json-encoded string
     * @return a {@link Map} consisting of the key/value pairs of the JSON-encoded string
     */
    @SuppressWarnings("unchecked")
    private Map<String, Object> getKeyValueMap(String rawJson) throws JsonParseException, JsonMappingException, IOException {
        return objectMapper.readValue(rawJson, HashMap.class);
    }


    /**
     * Retrieve an existing entity and copy the new changes onto the entity.
     *
     * @param changes a recently deserialized entity object that contains the new changes
     * @param rawJson the raw json string, used to determine which keys were passed to prevent
     *                copying unset/null values over to the persisted entity
     * @return the persisted entity with the new changes copied onto it
     * @throws NoSuchMethodException
     * @throws SecurityException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     */
    private Object copyObjectToPersistedEntity(Object changesObject, Map<String, Object> changesMap, Object id) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {

        Session session = sessionFactory.openSession();

        Object persistedObject =
                session.get(changesObject.getClass(), (Serializable) id);

        session.close();

        if(persistedObject == null) {
            throw new ValidationException(changesObject.getClass().getSimpleName() + " #" + id + " not found.");
        }

        Class<?> clazz = persistedObject.getClass();

        for(Method getterMethod : ReflectionUtils.getAllDeclaredMethods(clazz)) {

            Column column = getterMethod.getAnnotation(Column.class);

            //Column annotation is required
            if(column == null) {
                continue;
            }

            //Is the field allowed to be updated?
            if(!column.updatable()) {
                continue;
            }

            //Was this change a part of JSON request body?
            //(prevent fields false positive copies when certain fields weren't included in the JSON body)
            if(!changesMap.containsKey(BeanUtils.toFieldName(getterMethod))) {
                continue;
            }

            //Is the new field value different from the existing/persisted field value?
            if(ObjectUtils.equals(getterMethod.invoke(persistedObject), getterMethod.invoke(changesObject))) {
                continue;
            }

            //Copy the new field value to the persisted object
            log.info("Update " + clazz.getSimpleName() + "(" + id + ") [" + column.name() + "]");

            Object obj = getterMethod.invoke(changesObject);

            Method setter = BeanUtils.toSetter(getterMethod);

            setter.invoke(persistedObject, obj);

        }

        return persistedObject;
    }


    /**
     * Check if the recently deserialized entity object was populated with its ID field
     *
     * @param entity the object
     * @return an object value if the id exists, null if no id has been set
     */
    private Object getId(Object entity) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

        for(Method method : ReflectionUtils.getAllDeclaredMethods(entity.getClass())) {
            if(method.getAnnotation(Id.class) != null) {
                method.setAccessible(true);
                return method.invoke(entity);
            }
        }

        return null;
    }


    private <T> T parse(String json, Class<T> clazz) throws JsonParseException, IOException {
        try {
            return objectMapper.readValue(json, clazz);
        } catch(JsonMappingException e) {
            throw new ValidationException(e);
        }
    }

    public void setDoLog(boolean doLog) {
        this.doLog = doLog;
    }

}

答案 2 :(得分:0)

我不知道这是由于我使用的Spring版本(5)还是我做错了什么,但是这里的答案对我不起作用。我最后要做的是向所需的ObjectMapper注册一个RequestResponseBodyMethodProcessor。

PushCard.getObjectMapperForDTO()是我的方法,该方法返回一个已经具有正确的Mixins的ObjectMapper。您显然可以使用自己的方法,该方法可以根据需要进行配置。

我的配置类如下。

@EnableWebMvc
@Configuration
public class SidekickApplicationConfiguration implements WebMvcConfigurer {
    private static Logger logger = LoggerFactory.getLogger(SidekickApplicationConfiguration.class);

    @Autowired
    private RequestMappingHandlerAdapter requestHandler;

    @Bean
    RequestResponseBodyMethodProcessor registerReturnValueHandler() {
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new MappingJackson2HttpMessageConverter(PushCard.getObjectMapperForDTO()));

        logger.info("Registering RequestResponseBodyMethodProcessor with DTO ObjectMapper...");
        RequestResponseBodyMethodProcessor r = new RequestResponseBodyMethodProcessor(messageConverters);
        requestHandler.setReturnValueHandlers(Arrays.asList(r));
        return r;
    }
}