@JsonIgnore注解用來忽略某些字段,可以用在Field或者Getter方法上,用在Setter方法時,和Filed效果一樣。這個注解只能用在POJO存在的字段要忽略的情況,不能滿足現在需要的情況。
@JsonIgnoreProperties(ignoreUnknown = true),將這個注解寫在類上之后,就會忽略類中不存在的字段,可以滿足當前的需要。這個注解還可以指定要忽略的字段。使用方法如下:
@JsonIgnoreProperties({ "internalId", "secretKey" })
指定的字段不會被序列化和反序列化。
===========
代碼會返回tes對象為null
public class tes { private String a; private String b; public String getA() { return a; } public void setA(String a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } public static void main(String[] args) { String ss="{\"a\":\"aa\",\"c\":\"c\"}"; tes t= JsonUtil.fromJson(ss,tes.class); // tes t= new Gson().fromJson(ss,tes.class); } }
解決方案:
正確在class上加 @JsonIgnoreProperties(ignoreUnknown = true) public class tes 或者代碼控制 ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.readValue(json,cls);