杰克逊反序列化:未被认可的领域

时间:2013-08-29 21:24:11

标签: java json jackson

从教程中我得知这应该有效(简化示例):

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

3 个答案:

答案 0 :(得分:3)

您可以将ObjectMapper配置为忽略您在课堂上找不到的字段

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

如果没有以这种方式配置,它将在解析时抛出异常,如果它找到了一个它在你指定的类类型上无法识别的字段。

答案 1 :(得分:2)

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

答案 2 :(得分:1)

如果您从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;
    }
}