Is it possible to use Jackson to obtain value from Pojo Is it possible to use Jackson to obtain value from Pojo json json

Is it possible to use Jackson to obtain value from Pojo


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


You can serialize the Bean into a Json String, then deserialize the same Json String into a Map (just call ObjectMapper.readValue(JsonString, Map.class)) and then you can do Map.get("property") and you have it. Here is a one-liner solution:

String property = ((Map<String, Object>)mapper.readValue(mapper.writeValueAsString(bean), Map.class)).get("property").toString();