简体   繁体   中英

Parsing nested JSON Arrays using Jackson

Im using jacson to parse the following JSON array

[
  {
"target": "something",
"datapoints": [
  [
  null,
  1482223380
  ]]}]

Into this POJO

public class Response {

  private String target;
  private List<List<Double>> datapoints;

  public String getTarget() {
    return target;
  }

  public void setTarget(String target) {
    this.target = target;
  }

  public List<List<Double>> getData() {
    return datapoints;
  }

  public void setData(List<List<Double>> data) {
    this.datapoints = data;
  }
}

Using the following code

objectMapper.readValue(json, new TypeReference<List<Response>>() {});

This works partially, the outer list and the target is correct, however datapoints is null.

My initial solution is taken from this answere.

My question is, why are not datapoints not parsed as expected? Do this has something todo with the null values inside the array?

You could write a custom JsonDeserializer for the datapoints field.

class MyDatapointsDeserializer extends JsonDeserializer<List<List<Double>>> {

    private static final TypeReference<List<List<Double>>> TYPE_REF = 
            new TypeReference<List<List<Double>>>() {};

    @Override
    public List<List<Double>> deserialize(
            JsonParser jp, DeserializationContext ctxt) throws IOException {
        return jp.readValueAs(TYPE_REF);
    }
}

Then annotate the field accordingly.

@JsonDeserialize(using = MyDatapointsDeserializer.class)
private List<List<Double>> datapoints;

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