8

I need to create a map of @JsonProperty Values to Original field names.
Is it possible to achieve?

My POJO class:

public class Contact
{
  @JsonProperty( "first_name" )
  @JsonView( ContactViews.CommonFields.class )
  private String firstName;

  @JsonProperty( "last_name" )
  @JsonView( ContactViews.CommonFields.class )
  private String lastName;

  public String getFirstName()
    {
        return firstName;
    }

  public void setFirstName( String firstName )
    {       
        this.firstName = firstName;
    }

  public String getLastName()
    {
        return lastName;
    }

  public void setLastName( String lastName )
    {
        this.lastName = lastName;
    }
}

I need a map like:

{"first_name":"firstName","last_name":"lastName"}

Thanks in Advance...

1 Answers1

14

This should do what you are looking for:

public static void main(String[] args) throws Exception {

    Map<String, String> map = new HashMap<>();

    Field[] fields = Contact.class.getDeclaredFields();

    for (Field field : fields) {
        if (field.isAnnotationPresent(JsonProperty.class)) {
            String annotationValue = field.getAnnotation(JsonProperty.class).value();
            map.put(annotationValue, field.getName());
        }
    }
}

Using your Contact class as example, the output map will be:

{last_name=lastName, first_name=firstName}

Just keep in mind the above output is simply a map.toString(). For it to be a JSON, just convert the map to your needs.

dambros
  • 4,252
  • 1
  • 23
  • 39
  • Thanks! This was useful for me when I wanted to get the JsonProperty annotation on my enum, which is different than the raw enum value. `Field field = MyEnum.NAME.getClass().getField("NAME")` – LarryW Aug 29 '23 at 00:25