Reputation: 113
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...
Upvotes: 8
Views: 11192
Reputation: 4392
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.
Upvotes: 14