简体   繁体   English

如何使用 java 和 jackson api 获取 @JsonProperty 的值?

[英]How to get @JsonProperty 's value using java and jackson api?

In one of the cases in my project, I encountered a case where I need to fetch JSONPropoerty name to build another json object.在我的项目中的一个案例中,我遇到了需要获取 JSONPropoerty 名称来构建另一个 json object 的案例。

I have a pojo class:我有一个 pojo class:

 public class Records {
    @JsonProperty("NEWVALUE")
    private String new;
}

now in another class I need to create JSON Object using the json property names associated with my Record pojo class's @JsonProperty names. now in another class I need to create JSON Object using the json property names associated with my Record pojo class's @JsonProperty names.

I want something like我想要类似的东西

Record rec=new Record();
JsonNode tmpNode=new JsonNode();
String key= <somehow get value from rec object i.e. "NEWVALUE">
((ObjectNode) tmpNode).put(key, "abc"));

Is there any way to get the json property names associated with java field names.有没有办法获得与 java 字段名称关联的 json 属性名称。

Even so, Jackson , has classes like com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector , com.fasterxml.jackson.databind.introspect.AnnotatedField , etc... I would recommend to not use if it is really not required. Even so, Jackson , has classes like com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector , com.fasterxml.jackson.databind.introspect.AnnotatedField , etc... I would recommend to not use if it is really not required. They have really sophisticated API and works only for objects from com.fasterxml.jackson.databind.introspect which you need to create somehow.他们有非常复杂的API并且仅适用于您需要以某种方式创建的com.fasterxml.jackson.databind.introspect中的对象。

The easiest solution is to create public static final field and use in another class:最简单的解决方案是创建public static final字段并在另一个 class 中使用:

class Records {

    public static final String NEW_VALUE = "NEWVALUE";

    @JsonProperty(NEW_VALUE)
    private String value;
}

And you can use it as below:您可以按如下方式使用它:

((ObjectNode) tmpNode).put(Records.NEW_VALUE, "abc"));

Or, just use Reflection to read an annotation from given field.或者,只需使用Reflection从给定字段中读取注释。

See also:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM