Jackson takes many factors into account when naming a field for serialization into JSON. Is it possible to use those factors in reverse in order to retrieve the value of a field in a pojo based on the name it will have once serialized?
For example, given the bean
public class Bean{
private Bean2 prop;
@JsonProperty("property")
public Bean2 getProp();
}
Is it possible to get the value of prop
given only a configured ObjectMapper
, the string "property"
and an instance of Bean
?
I know about reflection, so if I could just get "prop"
or "getProp"
I would be pretty much good to go.
You can de-serialize given JSON String into Bean
.
Then You can find property using get()
method of JsonNode
and after that you can get value as POJO using treeToValue()
method.
E.g.
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(new ObjectMapper().writeValueAsString(bean), JsonNode.class);
JsonNode propertyNode = rootNode.get("property");
Class<?> propertyField = null;
Field []fields = Bean.class.getDeclaredFields();
for (Field field : fields){
//First checks for field name
if(field.equals("property")){
propertyField = field.getType();
break;
}
else{
//checks for annotation name
if (field.isAnnotationPresent(JsonProperty.class) && field.getAnnotation(JsonProperty.class).value().equals("property")) {
propertyField = field.getType();
break;
}
//checks for getters
else {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), Bean.class);
Method getMethod = pd.getReadMethod();
if (getMethod.isAnnotationPresent(JsonProperty.class) && getMethod.getAnnotation(JsonProperty.class).value().equals("property")) {
propertyField = field.getType();
break;
}
}
}
}
if(propertyField != null){
Object o = mapper.treeToValue(propertyNode, propertyField);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With