定义类如下,
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class TenantSpecialLinePo extends TenantLinePo
{
private static final long serialVersionUID = -1356444280247234290L;
private Integer tLineId;
……
}
反序列化
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
list = objectMapper.readValue(msgObject.getString("data"), TenantSpecialLinePo[].class);
提示错误:
Unrecognized field "azDeviceId" (class com.huawei.netmonitor.server.entity.tenantSpecilLine.TenantSpecialLinePo), not marked as ignorable
在网上搜索,原来是jackson版本错误混合使用导致,org.codehaus.jackson.annotate
(version 1.x),而ObjectMapper
的版本是com.fasterxml.jackson.databind (version 2.x)
https://stackoverflow.com/questions/20986995/jsonignoreproperties-not-working
仔细查看之前的代码,为什么原来代码没有报错
import org.codehaus.jackson.map.ObjectMapper;
TenantSpecialLineResponseBean tenantSpecialLineResponseBean = objectMapper.readValue(in, TenantSpecialLineResponseBean.class);
那么 这两个版本用法有什么区别,参照这里
https://blog.csdn.net/ClementAD/article/details/46416647
原来Jackson fasterxml是Jackson 2.0的新包名,1.x版本现在只提供bug-fix,而2.x版本还在不断开发和发布中。如果是新项目,建议直接用2x,即fasterxml jackson。
补充:
json字符串 反序列化成对象,除了使用@JsonIgnoreProperties 注解,还可以用下面方法配置:
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);