相关疑难解决方法(0)

使用Spring MVC for REST时,如何让Jackson能够打印出漂亮的JSON?

在使用Spring MVC开发REST服务的同时,我希望在开发中渲染JSON"漂亮打印",但在生产中正常(减少空白).

json spring-mvc pretty-print jackson

46
推荐指数
6
解决办法
4万
查看次数

注册器使用JAXB注释在Spring 3.1.2中MappingJackson2HttpMessageConverter

我有许多具有JAXB注释的实体,我想使用消息转换器将其转换为JSON.

我知道我读取JAXB注释的ObjectMapper有效:

String correctJsonText = jacksonObjectMapper.writeValueAsString(entityWithJAXB); 
Run Code Online (Sandbox Code Playgroud)

但是当我调用我的rest服务时,默认注册的MappingJacksonHttpMessageConverter(未配置为读取JAXB)似乎接管了 - 当忽略@XmlTransient时,由于循环引用而导致堆栈溢出...

如何配置Spring使用MappingJackson2HttpMessageConverter?

当前配置

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
        <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="jacksonObjectMapper" />
            <property name="supportedMediaTypes">
                <list>
                    <bean class="org.springframework.http.MediaType">
                        <constructor-arg index="0" value="application" />
                        <constructor-arg index="1" value="json" />
                        <constructor-arg index="2" value="UTF-8" />
                    </bean>
                </list>
            </property>

        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

<bean id="jaxbAnnotationInspector" class="com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector" />

<bean id="jacksonObjectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
    <property name="annotationIntrospector" ref="jaxbAnnotationInspector" />
</bean>
Run Code Online (Sandbox Code Playgroud)

REST服务

@RequestMapping(value="/{id}", method=RequestMethod.GET, produces = "application/json;charset=UTF-8")
public @ResponseBody EntityWithJAXB readEntityWithJAXB(@PathVariable int id, Model model) {
    return entityService.getById(id);
}
Run Code Online (Sandbox Code Playgroud)

依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.0.5</version>
</dependency> …
Run Code Online (Sandbox Code Playgroud)

spring json mocking jaxb jackson

9
推荐指数
1
解决办法
3万
查看次数

标签 统计

jackson ×2

json ×2

jaxb ×1

mocking ×1

pretty-print ×1

spring ×1

spring-mvc ×1