Peter Sabaini
Peter Sabaini

Reputation: 45

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

Upvotes: 1

Views: 3708

Answers (3)

Brent Worden
Brent Worden

Reputation: 10974

The Foo class needs an instance property of type Qux for automatic deserialization to work. The way the Foo class is currently defined, there is no destination property to inject the qux JSON object values.

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

Upvotes: 2

Luke Willis
Luke Willis

Reputation: 8580

It will work if you pull your Qux class out of 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;
    }
}

Upvotes: 2

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279960

You can configure ObjectMapper to ignore fields it doesn't find in your class with

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.

Upvotes: 3

Related Questions