3

In one of the cases in my project , I encountered a case where I need to fetch JSONPropoerty name to build another json object.

I have a 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.

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.

Mark
  • 28,783
  • 8
  • 63
  • 92
Anonymous
  • 1,726
  • 4
  • 22
  • 47
  • something like this https://stackoverflow.com/questions/4296910/is-it-possible-to-read-the-value-of-a-annotation-in-java – Ryuzaki L Nov 04 '19 at 21:59

1 Answers1

2

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.

The easiest solution is to create public static final field and use in another 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.

See also:

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146