Java 是否可以获取@JsonProperty的原始字段名?
我需要创建@JsonProperty值到原始字段名的映射。Java 是否可以获取@JsonProperty的原始字段名?,java,spring,jackson,objectmapper,Java,Spring,Jackson,Objectmapper,我需要创建@JsonProperty值到原始字段名的映射。可以实现吗 我的POJO课程: public class Contact { @JsonProperty( "first_name" ) @JsonView( ContactViews.CommonFields.class ) private String firstName; @JsonProperty( "last_name" ) @JsonView( ContactViews.CommonFields.clas
可以实现吗 我的POJO课程:
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;
}
}
我需要一张像这样的地图:
{"first_name":"firstName","last_name":"lastName"}
提前感谢…这应该满足您的需求:
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());
}
}
}
请记住,上面的输出只是一个
map.toString()
。要使其成为JSON,只需将映射转换为您的需要。您希望能够将jsonProperty值映射为字段名值,对吗?@dambros:Yes。JsonProperty到字段名的映射
{last_name=lastName, first_name=firstName}