简体   繁体   English

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

[英]Jackson Deserialization: unrecognized field

From the tutorial I had the impression that this should work (simplified example): 从本教程中,我觉得这应该可行(简化示例):

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

However, I get an error 但是,我得到一个错误

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

I'm running 2.2.2 我正在运行2.2.2

You can configure ObjectMapper to ignore fields it doesn't find in your class with 您可以使用以下方式配置ObjectMapper以忽略在类中找不到的字段:

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

If not configured this way, it will throw exceptions while parsing if it finds a field it does not recognize on the class type you specified. 如果未通过这种方式配置,则在解析过程中如果找到您指定的类类型无法识别的字段,它将在解析时引发异常。

The Foo class needs an instance property of type Qux for automatic deserialization to work. Foo类需要Qux类型的实例属性才能自动反序列化工作。 The way the Foo class is currently defined, there is no destination property to inject the qux JSON object values. 当前定义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;
       }
    }
}

It will work if you pull your Qux class out of Foo 如果将Qux类从Foo退出,它将起作用

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM