我正忙于Dropwizard应用程序,需要将一个数组作为 put
方法的参数之一注入(inject)到 POJO 中。不幸的是,该数组未得到正确处理,从而导致 Bad Request
响应。为了说明前端传递的 JSON 如下所示:
{
"name": "Jon",
"surname": "Doe",
"children": ["Chris", "Dave", "Sam"]
}
以及我的 Java 表示:
public class Person{
private String name;
private String surname;
private List<String> children;
public Person(){
}
@JsonProperty
public String getName(){
return name;
}
@JsonProperty
public void setName(String name){
this.name=name;
}
@JsonProperty
public String getSurname(){
return surname;
}
@JsonProperty
public void setsurname(String surname){
this.surname=surname;
}
@JsonProperty
public List<String> getChildren(){
return children;
}
@JsonProperty
public void setChildren(List<String> children){
this.children=children;
}
}
在我的资源类中:
@PUT
@Timed
@UnitOfWork
@Path("/{userid}")
public Response getData(@PathParam("userid") LongParam userId,
Person person) {
// Do some stuff with the person
}
如何正确处理 JSON 中数组的反序列化?
编辑
我正在使用角度前端,并且调用方法如下:
function(json){
return $http({
url: API_URL.people+"/update/personID",
method: "PUT",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: json
});
}
其中 json
参数包含姓名和 child ,如上所述。
最佳答案
看起来 GET 服务定义不正确。它不应该定义 Person
。
根据 http
方法定义,GET http 方法
不能有正文。因此,您不能将 Person
作为输入参数。
如果您需要将 Person
发送到服务,您可能需要根据您的要求将 http 方法更改为 POST 或其他方法(例如 PUT
)。
@GET
@Timed
@UnitOfWork
@Path("/{userid}")
public Response getData(@PathParam("userid") LongParam userId) {
// Do some stuff with the person
}
关于java - Dropwizard 反序列化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48747299/