Java MergingSettableBeanProperty-class And Method Code Example
Here is an example of using the MergingSettableBeanProperty
class from the com.fasterxml.jackson.databind package in the Jackson library to handle a merging property:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder;
import com.fasterxml.jackson.databind.introspect.SettableBeanProperty;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class MergingSettableBeanPropertyExample {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
SimpleModule module = new SimpleModule();
module.addDeserializer(MyObject.class, new MyObjectDeserializer());
mapper.registerModule(module);
MyObject obj = new MyObject();
obj.setMyField("myValue");
obj.setMyField2("myValue2");
String json = mapper.writeValueAsString(obj);
System.out.println(json);
MyObject obj2 = mapper.readValue(json, MyObject.class);
System.out.println(obj2.getMyField());
System.out.println(obj2.getMyField2());
}
}
class MyObject {
private String myField;
private String myField2;
public String getMyField() {
return myField;
}
public void setMyField(String myField) {
this.myField = myField;
}
public String getMyField2() {
return myField2;
}
public void setMyField2(String myField2) {
this.myField2 = myField2;
}
}
class MyObjectDeserializer extends JsonDeserializer<MyObject> {
@Override
public MyObject deserialize(JsonParser parser, DeserializationContext context) throws IOException {
MyObject obj = new MyObject();
JsonNode node = parser.getCodec().readTree(parser);
obj.setMyField(node.get("my_field").asText());
obj.setMyField2(node.get("my_field_2").asText());
return obj;
}
}
class MyPOJOPropertyBuilder extends POJOPropertyBuilder {
@Override
protected SettableBeanProperty _construct(AnnotatedMember member) {
SettableBeanProperty property = super._construct(member);
if (property != null) {
return new MergingSettableBeanProperty(property);
}
return property;
}
}