定義類如下,
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);
