背景
在调用其他业务方时,出现接口某些字段丢失问题。其他字段正常。但是通过http请求调用时参数返回正确。
class A {
private Long cId; //丢失字段
private String name; //正常
}
分析
定位问题出现在Feign反序列化过程中。
通过本地查看源码,发现问题出现在反序列化时,字段名转换出错了
com.fasterxml.jackson.databind.introspect#POJOPropertiesCollector
com.fasterxml.jackson.databind.util.BeanUtil#legacyManglePropertyName
@Slf4j
public class BeanUtilTest {
String baseName = "setCId";
String baseName = "setCId";
String baseName1 = "setCcId";
@Test
public void legacyManglePropertyName() {
// setCId | stdManglePropertyName to :cid
log.error("{} | legacyManglePropertyName to :{}", baseName, BeanUtil.legacyManglePropertyName(baseName, 3));
// setCcId | stdManglePropertyName to :ccId
log.error("{} | legacyManglePropertyName to :{}", baseName1, BeanUtil.legacyManglePropertyName(baseName1, 3));
}
@Test
public void stdManglePropertyName() {
// setCId | legacyManglePropertyName to :cid
log.error("{} | stdManglePropertyName to :{}", baseName, BeanUtil.legacyManglePropertyName(baseName, 3));
// setCcId | legacyManglePropertyName to :ccId
log.error("{} | stdManglePropertyName to :{}", baseName1, BeanUtil.stdManglePropertyName(baseName1, 3));
}
}
解决方案
1、修改字段名为全小写
2、在字段上使用指定注解,指定json中的字段名
class A {
@JsonProperty("cId")
private Long cId; //丢失字段
private String name; //正常
}
参考资料
springboot中的jackson配置及Jackson工具类分享_月慕向阳的博客-优快云博客_jackson配置类
https://www.jianshu.com/p/410aa00f6389
feign 序列化_Spring Feign 序列化机制_weixin_39777242的博客-优快云博客
spring cloud feign客户端调用JSON数据接口对自定义类型反序列化失败源码分析 - 腾讯云开发者社区-腾讯云