JsonIgnoreProperties

If you are using the Jackson project to parse JSON files than I recommend to use the “@JsonIgnoreProperties” Annotation. Assume that you have a JSON String like this, with 2 properties:

{
  "name" : "mike", 
  "sex" : "male"
}

If you want to parse that with Jackson, you have to create a class like this.


public class User {

private String name;
private String sex;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getSex() {
    return sex;
  }

  public void setSex(String sex) {
    this.sex = sex;
  }
}

And with Jackson you can map it like this:


ObjectMapper mapper = new ObjectMapper();
 User user = mapper.readValue(reader, User.class);

So far so good. As soon somebody adds a another Property to the JSON stream, your code breaks. Yes! 🙂
Because Jackson tries to map every Property from the JSON to your class. Assume somebody ads the Property “age” and the JSON looks now like this:

{
  "name" : "mike", 
  "sex" : "male",
  "age" : "19"
}

Now Jackson tries to map “age” to the User class. And because their is no getter and setter your code will break with a nice Exception. Happy Exception Handling 🙂
If you want to avoid this strange behavior, than put this Annotation on top of your User class: “@JsonIgnoreProperties(ignoreUnknown = true)”. With that Jackson will ignore unknown Properties.

I don’t know why I have to use this Annotation. For me it is pretty clear that an Exception occurs if I call an non existing setter. I mean ignoring unknown properties should be the default behavior. Everything else just doesn’t make any sense for me.

Published by Robert Reiz

CEO @ VersionEye. Passionated software developer since 1998.

One thought on “JsonIgnoreProperties

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: