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.

JsonAnySetter

I am using the Jackson JSON Lib in Java to process JSON. If you don’t know how JSON works in Ruby, you will like this project. Anyway. If you have dynamic JSON stream where the property names are not always the same, than you need the “@JsonAnySetter” Annotation. With that you can map dynamic Properties to a map.


private Map<String, Object> all = new HashMap<String, Object>();

@JsonAnySetter
public void set(String name, Object value) {
   all.put(name, value);
}

public Map<String, Object> getAll() {
   return all;
}

public void setAll(Map<String, Object> all) {
   this.all = all;
}

That worked out for me, for a String – String pair.