Java and JSON processing

Java and JSON processing

The best processor we've used is Jackson.

Jackson

Use version 2 if possible.

Dynamic Beans

To add dynamic fields into your model, you can use the annotation @JsonAnyGetter on a method that returns a Map. This map will be serialized on the same level as the the other fields.

public class Person {
    private String name;
    private Map<String, Object> otherFields = new HashMap<String, Object>();

    @JsonAnyGetter
    public Map<String,Object> any() {
        return otherFields;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
Person person = new Person();
person.setName("MagicMonster");
person.set("age", 300);

// serialize
new ObjectMapper().writeValue(System.out, person);

The above will output

{"name":"MagicMonster","age":300}

See sample/DynaBean.java.

Published: Friday, 30 January 2015