Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the original field names of @JsonProperty?

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...

like image 787
Paramesh Shiyaam Avatar asked Mar 31 '16 08:03

Paramesh Shiyaam


People also ask

What is difference between JsonProperty and JsonAlias?

@JsonProperty can change the visibility of logical property using its access element during serialization and deserialization of JSON. @JsonAlias defines one or more alternative names for a property to be accepted during deserialization.

What is JsonProperty annotation?

The @JsonProperty annotation is used to map property names with JSON keys during serialization and deserialization. By default, if you try to serialize a POJO, the generated JSON will have keys mapped to the fields of the POJO.

Is JsonProperty needed?

You definitely don't need all those @jsonProperty . Jackson mapper can be initialized to sereliazie/deserialize according to getters or private members, you of course need only the one you are using. By default it is by getters.

How do I ignore JsonProperty?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.


1 Answers

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.

like image 116
dambros Avatar answered Oct 20 '22 14:10

dambros