杰克逊反序列化:无法识别的领域

从教程我有一个印象,这应该工作(简化的例子):

public class Foo {
    private String bar;
    public String getBar() {
        return bar;
    }
    public void setBar(String bar) {
        this.bar = bar;
    }
    public static class Qux {
        private String foobar;
        public String getFoobar() {
            return foobar;
        }
        public void setFoobar(String foobar) {
            this.foobar = foobar;
        }
    }
}
...

String in = "{ "bar": "123", "qux" : {"foobar": "234"}}";
ObjectMapper mapper = new ObjectMapper();
Foo obj = mapper.readValue(in, Foo.class);

但是,我收到一个错误

UnrecognizedPropertyException: Unrecognized field "qux" (Class Foo), not marked as ignorable

我正在运行2.2.2


如果你将你的Qux课程从Foo Qux出来,它将起作用

public class Foo {
    private String bar;

    // added this
    private Qux qux;

    public String getBar() {
        return bar;
    }
    public void setBar(String bar) {
        this.bar = bar;
    }

    // added getter and setter
    public Qux getQux() {
        return qux;
    }
    public void setQux(Qux qux) {
        this.qux = bar;
    }
}

public static class Qux {
    private String foobar;
    public String getFoobar() {
        return foobar;
    }
    public void setFoobar(String foobar) {
        this.foobar = foobar;
    }
}

您可以将ObjectMapper配置为忽略它在类中找不到的字段

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

如果没有这样配置,它会在解析时抛出异常,如果它找到一个它不能识别你指定的类类型的字段。


Foo类需要Qux类型的实例属性以使自动反序列化工作。 Foo类当前被定义的方式,没有目标属性来注入qux JSON对象值。

public class Foo {
   private String bar;

   public String getBar() {
       return bar;
   }

   public void setBar(String bar) {
       this.bar = bar;
   }

   // additional property 
   private Qux qux;

   public Qux getQux() {
       return qux;
   }

   public void setQux(Qux value) {
       qux = value;
   }

   public static class Qux {
       private String foobar;

       public String getFoobar() {
         return foobar;
       }

       public void setFoobar(String foobar) {
           this.foobar = foobar;
       }
    }
}
链接地址: http://www.djcxy.com/p/45625.html

上一篇: Jackson Deserialization: unrecognized field

下一篇: RS request with JAX