简体   繁体   中英

JSON dynamic field name with Jackson

I use an API that provides a swagger.yaml from it I generated following class:

@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;
  }

 /* ... */
}

Using the API to request a SpecificationHistoryRespone for a specific "specification" returns following 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": {
    /*...*/
  }
}

Using the JacksonJsonProvider I cannot get specification_key as it always tries to deserialize a value key which does not exist.

Okay the automatically created code needs quite some editing and should look like this to work with dynamic field names:

@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;
  }
 /* ... */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM