Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Jackson to obtain value from Pojo

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.

like image 345
kag0 Avatar asked Dec 10 '15 09:12

kag0


1 Answers

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);

        }
like image 147
Sachin Gupta Avatar answered Oct 11 '22 22:10

Sachin Gupta