@JsonAnySetter
@JsonAnySetter allows you the flexibility of using a Map as a standard properties. On de-serialization, the properties from JSON will simply be added to the map.
Let's see how this works - we'll use @JsonAnySetter to deserialize the entity ExtendableBean:
public class ExtendableBean {
public String name;
private Map<String, String> properties = new HashMap<>();
@JsonAnySetter
public void add(String key, String value) {
properties.put(key, value);
}
@Override
public String toString() {
return "ExtendableBean{" +
"name='" + name + '\'' +
", properties=" + properties +
'}';
}
}
This is the JSON we need to deserialize:
{
"name": "My bean",
"attr2": "val2",
"attr1": "val1"
}
And here's how this all ties in together:
@Test
public void test01() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json
= "{\"name\":\"My bean\",\"attr2\":\"val2\",\"attr1\":\"val1\", \"attr11\":\"val11\", \"attr1\":\"val11111\"}";
ExtendableBean extendableBean = mapper.readValue(json, ExtendableBean.class);
System.out.println(extendableBean);
Assert.assertEquals("val11111", extendableBean.getProperties().get("attr1"));
Assert.assertEquals("val11", extendableBean.getProperties().get("attr11"));
}