我想反序列化以下JSON:
{
"name":"Test",
"owners":[
{
"username":"admin"
}
]
}
关注对象
public class ShoppingList {
private String name;
private final Set<ShoppingListUser> owners;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<ShoppingListUser> getOwners() {
return owners;
}
@JsonDeserialize(as = HashSet.class, contentAs = ShoppingListUser.class)
public void setOwners(Set<ShoppingListUser> owners) {
getOwners().clear();
if (owners != null) {
getOwners().addAll(owners);
}
}
}
我的控制器看起来像这样:
@RestController
@RequestMapping(value = "/api/shoppingLists", consumes = "application/json", produces = "application/json")
public class ShoppingListController {
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Resource<ShoppingList>> addShoppingList(@RequestBody ShoppingList shoppingList)
throws ShoppingListException {
//DoStuff
}
所有者的类型为 ShoppingListUser :
public class ShoppingListUser {
private String username;
private String password;
//Getters and Setters
}
我的问题是当我使用给定的JSON向此控制器发送一个后请求时,响应将是:
{&#34; timestamp&#34;:1435965015546,&#34; status&#34;:400,&#34; error&#34;:&#34; Bad Request&#34;,&#34; exception& #34;:&#34; org.springframework.http.converter.HttpMessageNotReadableException&#34;,&#34; message&#34;:&#34;无法读取JSON:模板不能为空或空! (通过参考链:de.klem.shopping.list.ShoppingList [\&#34; owner \&#34;] - &gt; java.util.LinkedHashSet [0]);嵌套异常是com.fasterxml.jackson.databind.JsonMappingException:模板不能为null或为空! (通过参考链:de.klem.shopping.list.ShoppingList [\&#34; owner \&#34;] - &gt; java.util.LinkedHashSet [0])&#34;,&#34; path&# 34;:&#34; / API / shoppingLists&#34;}
我不了解事件为何在此异常中发生LinkedHashSet。我没有告诉杰克逊使用HashSet.class
来反序集吗?
有人看到我的错误吗?我不能:(
要获得完整的代码,请随时访问我的github repo:https://github.com/Yannic92/ShoppingList/blob/master/src/main/java/de/klem/shopping/list/ShoppingList.java
运行应用程序所需的只是Maven和Java。
user:admin
密码:密码