java - Spring MVC 上使用不同字段名称的 JSON 序列化

标签 java json spring-mvc serialization

我一直在开发一个 Controller ,我想在其中返回 json 字符串作为响应。但问题是,我想在序列化/反序列化期间更改一些字段名称,但我不想在实体对象上使用丑陋的注释。

可以说

@Controller
@RequestMapping("/kfc/brands")
public class JSONController {

    @RequestMapping(value="{name}", method = RequestMethod.GET)
    public @ResponseBody Shop getShopInJSON(@PathVariable String name) {

        Shop shop = new Shop();
        shop.setName(name);
        shop.setStaffNames(new String[]{"mkyong1", "mkyong2"});

        return shop;

    }

}

public class Shop {
        String name;
        String staffNames[];
        String location;

        //getter and setter methods

    }

我希望 Controller 返回 staffNames 作为 Staff_nameslocation 作为地址,而不使用任何注释。

我认为必须有一个自定义对象映射器结构,但找不到合适的示例。我在序列化代码中手动设置字段名称没有问题。

PS:示例取自mkyong

最佳答案

要启用从 Camel 案例字段名称(如 firstName)到下划线字段名称(如 field_name)的转换,您应该注册一个自定义 json2Object Conveter 我想您有 spring 3.1 或更高版本

  • 对于第 1-1 步和第 1-2 步,您仅执行其中一项,而不是同时执行两项。

<强>1。配置您的上下文

1-1。如果您使用 XML 配置,那么您可以将此代码放入配置文件中

    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <!-- the important part start from here-->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper" ref="objectMapper" />
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <bean id="objectMapper"
        class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
        <property name="propertyNamingStrategy" >
        <util:constant static-field="com.fasterxml.jackson.databind.PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES"/>
        <property name="indentOutput" value="true"/>
        </property>
    </bean>

1-2。如果您使用编程配置

 @Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
                .indentOutput(true)
                .propertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }

}

2.获取依赖

下载这些 jar 并将它们放入您的应用程序 jackson-annotations-2.7.2jackson-core-2.7.2jackson-databind-2.7 .2 Here is the Maven repository

此转换器将转换带有此 header 的所有 REST 消息 Content-Type=application/json

PS: this converter will not convert your json message to string since String doesn't have a default constructor , to read you JSON message as string in your controller you use Content-Type=applciation/text in your client message header

关于java - Spring MVC 上使用不同字段名称的 JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35770875/

相关文章:

java - 让 Eclipse 识别导入

java - 将字符串转换为 HashMap

java - 对 REST Assured 浮点比较的混淆

java - 无法反序列化 `java.util.ArrayList` 的实例

java - 如何使用 Spring security 保护 URL?

java - 如何在现有的 tomcat Web 应用程序上实现 SSO

java - 异常 java.net.SocketException : Connection reset

python - Python 2.7.9 中的无效控制字符错误

Spring在tomcat 5.5部署问题

java - 空字符串字段作为空字段