Our preferred processor is Jackson.
Jackson
Use version 2 where 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 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);
new ObjectMapper().writeValue(System.out, person);
The above will output
{"name":"MagicMonster","age":300}