【问题标题】:Is it possible to get the original field names of @JsonProperty?是否可以获得@JsonProperty 的原始字段名称?
【发布时间】:2016-07-19 14:07:34
【问题描述】:

我需要创建一个@JsonProperty 值到原始字段名称的映射。
可以实现吗?

我的 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"}

在此先感谢...

【问题讨论】:

  • 您希望能够将 jsonProperty 值映射到字段名称值,对吗?
  • @dambros:是的。 JsonProperty 到 FieldNames 的映射

标签: java spring jackson objectmapper


【解决方案1】:

这应该可以满足您的需求:

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());
        }
    }
}

以您的 Contact 类为例,输出映射将是:

{last_name=lastName, first_name=firstName}

请记住,上面的输出只是一个map.toString()。要使其成为 JSON,只需将地图转换为您的需要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2021-05-27
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    相关资源
    最近更新 更多