jackson json转bean忽略没有的字段 not marked as ignorable

@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);

猜你喜欢

转载自wjg-java.iteye.com/blog/2324644