杰克逊{J}动态字段名

时间:2017-08-16 08:05:14

标签: java json jackson

我使用了一个API,它提供了一个swagger.yaml,我在下面的类中生成了它:

@ApiModel(description="the paginated history of the specification attributes values")
public class SpecificationHistoryResponse  {

  @ApiModelProperty(example = "null", value = "the array of historic values is named with the specification attributes key")
  private List<SpecificationResponse> key = new ArrayList<SpecificationResponse>();
  @ApiModelProperty(example = "null", value = "")
  private Pagination pagination = null;

 /**
   * the array of historic values is named with the specification attributes key
   * @return key
  **/
  public List<SpecificationResponse> getKey() {
    return key;
  }

  public void setKey(List<SpecificationResponse> key) {
    this.key = key;
  }

  public SpecificationHistoryResponse key(List<SpecificationResponse> key) {
    this.key = key;
    return this;
  }

  public SpecificationHistoryResponse addKeyItem(SpecificationResponse keyItem) {
    this.key.add(keyItem);
    return this;
  }

 /* ... */
}

使用API​​为特定“规范”请求SpecificationHistoryRespone返回以下JSON:

{
  "specification_key": [
    {
      "value": "0.02242",
      "source_timestamp": "2017-08-09T13:10:04.177Z"
    },
    {
      "value": "0.0124",
      "source_timestamp": "2017-08-11T13:16:04.177Z"
    }
    /*...*/
  ],
  "pagination": {
    /*...*/
  }
}

使用JacksonJsonProvider我无法获得specification_key,因为它始终会尝试反序列化不存在的值key

1 个答案:

答案 0 :(得分:0)

好的,自动创建的代码需要进行一些编辑,看起来应该像动态字段名一样:

@ApiModel(description="the paginated history of the specification attributes values")
public class SpecificationHistoryResponse  {

  @ApiModelProperty(example = "null", value = "the array of historic values is named with the specification attributes key")
  @JsonAnySetter
  private Map<String, List<SpecificationResponse>>  key = new HashMap<>();
  @ApiModelProperty(example = "null", value = "")
  private Pagination pagination = null;

 /**
   * the array of historic values is named with the specification attributes key
   * @return key
  **/
  public Map<String, List<SpecificationResponse>>  getKey() {
    return key;
  }

  public void setKey(Map<String, List<SpecificationResponse>> key) {
    this.key = key;
  }

  public SpecificationHistoryResponse key(Map<String, List<SpecificationResponse>>  key) {
    this.key = key;
    return this;
  }
 /* ... */
}