【问题标题】:Wrap a primitive returned from a Spring controller into json将从 Spring 控制器返回的原语包装成 json
【发布时间】:2014-12-09 09:56:11
【问题描述】:

现在,我正在使用这样的东西:

@RequestBody
@RequestMapping("whatever")
public ObjectWrapper<Integer> foo() {
    return new ObjectWrapper<>(42);
}

我想做的是用以下方式重写方法

@RequestBody
@RequestMapping("whatever")
public int foo() {
    return 42;
}

在它被序列化(由杰克逊)并被写入响应之前,将 42(或任何其他原语)包装到 ObjectWrapper 中。我想知道这是否真的可行,如果可以,该怎么做。

【问题讨论】:

    标签: json spring-mvc jackson


    【解决方案1】:

    由于我误解了你的问题,我更新了我的答案:

    public class CustomObjectMapper extends ObjectMapper {
        public CustomObjectMapper() {
            super();
            super.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
        }
    }
    

    添加到默认消息转换器:

        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper" />
            </bean>  
        </mvc:message-converters>
    
    <bean id="jacksonObjectMapper" class="com.mysite.CustomObjectMapper" />
    

    但是这可能不会产生您想要的输出。

    最好的办法是编写您自己的序列化程序并将其与您的自定义对象映射器一起使用,并将原语包装在您的序列化程序中。

    这是相关的:https://github.com/FasterXML/jackson-databind/issues/34

    【讨论】:

    • 我一开始误解了你的问题并更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多