[英]How to map JSON to Java Object
在我的网络服务中,我正在将发给请求的json发送到服务器。 在服务器中,我需要将此信息放入调用函数的参数中。
这是我在服务器端的功能:
@Path("/myapp/myfunction/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class SiderRecommender {
@POST
@Path("recs")
public Response getRecommendations(User usr) {
// Here I want to access request payload inside
//usr object. For example :
// System.out.println("limit sending by client:"+usr.getLimit());
// System.out.println("size of List sent by client:"+usr.getNames().size());
}
}
这是我的User类:
@XmlRootElement
public class User {
private List<String> names;
private int limit;
public List<String> getNames() {
return names;
}
public void setNames(List<String> names) {
this.names = names;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
}
最后,这就是我在客户端上发送请求的方式:
var url = 'http://localhost:8080/myapp/myfunction/recs';
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send(JSON.stringify({"names":[{"names":"SampleName1"}, {"names":"SampleName2"},{"names":"SampleName3"}],"limit":100 }));
我认为,JSON.stringify()中的语法可能会犯一个错误。 看起来像对吗?
编辑我顺便说一句使用杰克逊。
EDIT2
在浏览器中,出现此错误:
Can not deserialize instance of java.lang.String out of START_OBJECT token
at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@6508327b; line: 1, column: 10] (through reference chain: com.mypackage.User["names"])
问题出在从JavaScript传递的JSON对象上。
{
"names": [
{
"names": "SampleName1"
},
{
"names": "SampleName2"
},
{
"names": "SampleName3"
}
],
"limit": 100
}
您在“名称”下具有“名称”,该名称将映射到Java对象中的List<Map<String,String>>
。
更改Java对象或更改JSON对象(如下所示)以将其映射到List<String>
{
"names": [
"SampleName1",
"SampleName2",
"SampleName3"
],
"limit": 100
}
下图取自http://json.org/
JSON.stringify应该适合您的用例。 您没有提到您要面对的确切问题是什么,但是您的json似乎不正确(与您尝试将其映射到的对象相比)。
您的域对象被命名为IdsRequest,您的服务使用了User,并且您的json的名称包含一组名称和限制。 在您的json中,根元素是“名称”,其中包含名称数组,这不是您的域对象User的样子。 因此,在映射两者时会出现错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.