[英]Spring Hateoas error from EntityModel : Content is not a Map
我正在將spring-hateoas
從0.20.0.RELEASE
升級到1.3.7
我將ResourceSupport
替換為RepresentationModel
,將Resource
替換為RepresentationModel
。
在反序列化 DTO 的JSON
時,我遇到了一個異常,它在舊版本中運行良好。
帶有舊 Hateoas 版本的 DTO
public class Employee extends ResourceSupport implements Serializable {
@JsonProperty("id")
private Long id;
@JsonProperty("name")
private String name;
}
public class EmployeeResource extends Resource<Employee> {
EmployeeResource(){
super(new Employee());
}
}
帶有新 Hateoas 版本的 DTO
public class Employee extends RepresentationModel<Employee> implements Serializable {
@JsonProperty("id")
private Long id;
@JsonProperty("name")
private String name;
}
public class EmployeeResource extends EntityModel<Employee> {
EmployeeResource(){
super(new Employee());
}
}
要反序列化的JSON
文件employee.json
{
"employees": [
{
"id": 1,
"name": "Test",
"links": [
{
"rel": "self",
"href": "api/employees/1"
}
]
}
]
}
反序列化測試用例
@Test
public void test() throws IOException {
ObjectMapper mapper = new ObjectMapper();
InputStream inputStream = EmpTest.class.getClassLoader().getResourceAsStream("employee.json");
JsonNode node = mapper.readTree(IOUtils.toByteArray(inputStream));
TypeFactory typeFactory = mapper.getTypeFactory();
CollectionType listType = typeFactory.constructCollectionType(ArrayList.class, EmployeeResource.class);
List resultList = mapper.convertValue(node.findValue("employees"), listType);
System.out.println(resultList);
}
例外
java.lang.IllegalArgumentException: Content is not a Map! (through reference chain: java.util.ArrayList[0]->com.test.EmployeeResource["id"])
at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3589)
at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3530)
at com.test.EmpTest.test(EmpTest.java:60)
Caused by: java.lang.IllegalStateException: Content is not a Map!
at org.springframework.util.Assert.state(Assert.java:70)
at org.springframework.hateoas.EntityModel.getOrInitAsMap(EntityModel.java:158)
at org.springframework.hateoas.EntityModel.setPropertiesAsMap(EntityModel.java:149)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.fasterxml.jackson.databind.introspect.AnnotatedMethod.callOnWith(AnnotatedMethod.java:130)
at com.fasterxml.jackson.databind.deser.SettableAnyProperty.set(SettableAnyProperty.java:172)
... 33 more
從EntityModel
的super()
構造函數中刪除new Employee()
解決了這個問題,但不確定原因。
public class EmployeeResource extends Resource<Employee> {
EmployeeResource(){
super();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.