当前位置:  开发笔记 > 编程语言 > 正文

是否有可能使用杰克逊从Pojo获得价值

如何解决《是否有可能使用杰克逊从Pojo获得价值》经验,为你挑选了1个好方法。

在将字段序列化为JSON时,Jackson会考虑许多因素.是否可以反过来使用这些因子,以便根据序列化后的名称检索pojo中字段的值?

例如,给定bean

public class Bean{
    private Bean2 prop;

    @JsonProperty("property")
    public Bean2 getProp();
}

是否有可能只获得prop给定的值ObjectMapper,字符串"property"和实例Bean

我知道反思,所以如果我能得到,"prop"或者"getProp"我会非常好.



1> Sach141..:

您可以将给定的JSON字符串反序列化为Bean。然后,您可以使用的get()方法查找属性,然后使用方法JsonNode 获得作为POJO的值treeToValue()

例如

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

        }

推荐阅读
wurtjq
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有