背景
1.有2个项目a,b,使用了同一个redis服务中的对象数据,key-value
"test":{"a":null,"b":null}
2.项目a,新增了一个字段c,并编辑了redis中的数据
"test":{"a":null,"b":null,"c":null}
3.项目a可以正常运行,但是项目b获取test的val时,反序列化失败
org.springframework.data.redis.serializer.SerializationException:
Could not read JSON:
Unrecognized field "c" (class com.ty.test),
not marked as ignorable (2 known properties: "a", "b"])
原因
反序列化的时候没有找到对应的set方法
/**
* Helper method called for an unknown property, when using "vanilla"
* processing.
*
* @param beanOrBuilder Either POJO instance (if constructed), or builder
* (in case of builder-based approach), that has property we haven't been
* able to handle yet.
*/
protected void handleUnknownVanilla(JsonParser p, DeserializationContext ctxt,
Object beanOrBuilder, String propName)
throws IOException
{
if (_ignorableProps != null && _ignorableProps.contains(propName)) {
handleIgnoredProperty(p, ctxt, beanOrBuilder, propName);
} else if (_anySetter != null) {
try {
// should we consider return type of any setter?
_anySetter.deserializeAndSet(p, ctxt, beanOrBuilder, propName);
} catch (Exception e) {
wrapAndThrow(e, beanOrBuilder, propName, ctxt);
}
} else {
// Unknown: let's call handler method
handleUnknownProperty(p, ctxt, beanOrBuilder, propName);
}
}
/**
* Method called when a JSON property is encountered that has not matching
* setter, any-setter or field, and thus cannot be assigned.
*/
@Override
protected void handleUnknownProperty(JsonParser p, DeserializationContext ctxt,
Object beanOrClass, String propName)
throws IOException
{
if (_ignoreAllUnknown) {
p.skipChildren();
return;
}
if (_ignorableProps != null && _ignorableProps.contains(propName)) {
handleIgnoredProperty(p, ctxt, beanOrClass, propName);
}
// Otherwise use default handling (call handler(s); if not
// handled, throw exception or skip depending on settings)
super.handleUnknownProperty(p, ctxt, beanOrClass, propName);
}
解决方法
在每个redis的实体类上新增注解
//添加注解,忽略不存在的key
@JsonIgnoreProperties(ignoreUnknown = true)
public class Test