嵌套列表与 RestTemplate 交换

问题描述 投票:0回答:1

java.lang.IllegalArgumentException:无法从数组值(令牌

.dto.Person
)中反序列化
JsonToken.START_ARRAY
类型的值 在 [来源:未知;行:-1,列:-1](通过引用链:java.util.HashMap[])

JSON

{
  "scully": [
    {
      "beginDate": "2017-10-14",
      "endDate": "2017-10-18",
      "absences": [
        {
          "name": "Annual Leave",
          "number": "1_1",
          "type": "AL",
          "beginDate": "2017-10-14",
          "endDate": "2017-10-17",
          "status": "Checked, OK",
          "workingDays": 2.5,
          "isBeginDateHalfDay": false,
          "isEndDateHalfDay": true
        },
        {
          "name": "Annual Leave",
          "number": "1_2",
          "type": "AL",
          "beginDate": "2017-10-18",
          "endDate": "2017-10-18",
          "status": "Checked, Rejected",
          "workingDays": 0.5,
          "isBeginDateHalfDay": true,
          "isEndDateHalfDay": false
        }
      ]
    }
  ]
}
`@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
    @JsonProperty("BeginDate")
    public String beginDate;
    public String endDate;
    @JsonProperty("Absences")
    public List<Absence> absences;
}

`@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Absence {
    public String number;
    public String beginDate;
    public boolean isBeginDateHalfDay;

    public String type;

    public String name;
    public String endDate;
    public boolean isEndDateHalfDay;
    public boolean isAfternoonHalfDay;
    public String statusIdentifier;
    public double workingDays;
    public boolean isForenoonHalfDay;
    public String status;
}``

` ResponseEntity response = restTemplate.exchange( uriBuilder.toUriString(), HttpMethod.GET, httpEntity, new ParameterizedTypeReference() { });

    HashMap<String, Person> objects = response.getBody();
    // mapping der ResponseEntity zu Person Objekt...
    ObjectMapper mapper = new ObjectMapper();

    mapper.convertValue(objects, new TypeReference<HashMap<String, Person>>() {
    });
    return objects;`
spring boot spring-resttemplate
1个回答
0
投票

使用

TypeReference<HashMap<String, List<Person>>>()
因为json中的
scully
键有
List
Person
对象

mapper.convertValue(objects, new TypeReference<HashMap<String, List<Person>>>() {
});

并确保

@JsonPropert
注释中的属性名称与 json

匹配
@JsonProperty("beginDate")
public String beginDate;

@JsonProperty("absences")
public List<Absence> absences;
© www.soinside.com 2019 - 2024. All rights reserved.