【问题标题】:Auto detection Jackson for Spring自动检测 Jackson for Spring
【发布时间】:2015-01-13 21:38:08
【问题描述】:

我正在开发一个使用 Spring 框架和 Jackson 的项目。但是,我找不到一个地方,它被塞住了。我查看了网络上的许多示例,其中大多数使用 org.springframework.http.converter.json.MappingJacksonHttpMessageConverter 类的 bean 来允许对 @ResponseBody 进行反序列化。 所以,我找不到任何对 MappingJacksonHttpMessageConverter 的引用。

我的问题:spring 框架会自动使用 Jackson,如果它会在其类路径中找到它来将 JSON 转换为 @ResponseBody 对象吗?

还有哪些其他方法可以启用 Jackson?

【问题讨论】:

    标签: java spring spring-mvc jackson


    【解决方案1】:

    如果您使用@EnableWebMvc 或通过XML 使用标签<mvc:annotation-driven /> 连接您的spring 项目,您将启用一系列功能。您可以阅读original Spring docs 中的详细功能列表。

    启用的功能之一是支持@RequestBody 方法参数和@ResponseBody 方法返回值。这是通过HttpMessageConverter 组件完成的,并且为使用@RequestMapping@ExceptionHandler 注释的方法启用了该功能。

    下面列出了默认注册的转换器:

    • ByteArrayHttpMessageConverter 转换字节数组。
    • StringHttpMessageConverter 转换字符串。
    • 对于所有媒体类型,ResourceHttpMessageConverterorg.springframework.core.io.Resource 相互转换。
    • SourceHttpMessageConverterjavax.xml.transform.Source 相互转换。
    • FormHttpMessageConverter 将表单数据与 MultiValueMap 相互转换。
    • Jaxb2RootElementHttpMessageConverter 将 Java 对象转换为 XML 或从 XML 转换 - 如果 JAXB2 存在于类路径中,则添加。
    • MappingJackson2HttpMessageConverter(或 MappingJacksonHttpMessageConverter)与 JSON 相互转换 - 如果 Jackson 2(或 Jackson)出现在类路径中,则添加。
    • AtomFeedHttpMessageConverter 转换 Atom 提要 - 如果 Rome 存在于类路径中,则添加。
    • RssChannelHttpMessageConverter 转换 RSS 提要 - 如果 Rome 存在于类路径中,则添加。

    因此,如果您有一个 web 启用 项目,Jackson 在类路径上可用,Spring 将自动转换来自带有 @ResponseBody 注释的控制器方法的返回值(如果客户端调用者接受JSON 这意味着接受标头通常必须设置为application/json)。

    如果您希望覆盖HttpMessageConverters,您可以实现以下内容:

    @Configuration
    @EnableWebMvc
    public class YourConfiguration extends WebMvcConfigurerAdapter {
        @Override
            public void configureMessageConverters(
                    List<HttpMessageConverter<?>> converters) {
    
                // Do your magic, override your stuff
            }
    }
    

    关于如何自定义的很好的介绍,例如Jackson 转换器,您可以阅读this article from DZone about Customizing HttpMessageConverters with Spring Boot and Spring MVC

    【讨论】:

    • 谢谢!这就是我要找的东西!
    • 如果我需要一些自定义,我可以覆盖 MappingJackson2HttpMessageConverter 吗?
    • 谢谢! +一些字符:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 2016-01-14
    • 1970-01-01
    • 2016-09-18
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多