SpringBoot+json+postman post时候传参null
这家伙,我搞了两天。 get的时候啥事没有,post就出现这傻* 样子,特么的给我气炸了 快。
问题
==> Preparing: INSERT INTO Student(Sno,Sname,Ssex,Sage,Sdept) VALUES (?,?,?,?,?)
==> Parameters: 110(String), 孙悟空(String), 男(String), 100(String), 10010(String)
<== Updates: 1
然后我发现了这篇文章springboot post接口接受json时,转换为对象时,属性都为null
我真的太喜欢会读底层源码的银儿了。我理解的就是springboot默认的HttpMessageConverter解析jason时,用的转换器是MappingJackson2HttpMessageConverter。命名策略变为下划线+小写风格。
解决方法
1. 添加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
2.修改 yml文件
jackson:
property-naming-strategy: LOWER_CAMEL_CASE
3.将springboot默认的HttpMessageConverter替换为阿里的FastJson转换器
package com.example.wangyue;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
/**
* Created by conan on 2019/1/7.
*/
@Configuration
public class MyWebmvcConfiguration extends WebMvcConfigurationSupport {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
{
//调用父类配置
super.configureMessageConverters(converters);
//创建消息转换器
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//创建配置类
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//返回内容的过滤
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty
);
fastConverter.setFastJsonConfig(fastJsonConfig);
//将fastjson添加到视图消息转换器列表内
converters.add(fastConverter);
}
}
然后再次尝试,艾玛,快乐快乐~好了
复盘
虽然解决了问题,但是基本原来,还是不懂。所以完成这个小demo之后,要好好读源码。加油了!