[英]Unable to parse JSON object to Java Object in Springs Controller
I am wrestling with this JSON to Java Object conversion. 我正在努力将JSON转换为Java Object。 Here is my client side JavaScript code where it sends the JSON to Ajax call. 这是我的客户端JavaScript代码,它将JSON发送到Ajax调用。
var college = {
collegeName : $("#collegeNameID").val(),
estYear : $("#estYear").val(),
universityOrBoardName : $("#university").val(),
website : $("#webSite").val()
};
var address = {
city : $("#cityID").val(),
district: $("districtID").val()
};
ajaxResult = $.ajax({
url : urls,
async : false,
cache : false,
type : "POST",
dataType : "json",
contentType : "application/json",
mimeType : "application/json",
data : JSON.stringify({ College : college, Address: address}),
mimeType : "application/json",
success : function(result) {
return result;
}
Here is my Pojo class which are mapped to the respective JSON. 这是我的Pojo类,它们映射到相应的JSON。
Address.java Address.java
private String district;
private String city;
(there are other member variables for which I will not be getting the input from the Client side. I will be setting those in server side)
College.java College.java
private String collegeName;
private String universityOrBoardName;
private String website;
(there are other member variables for which I will not be getting the input from the Client side. I will be setting those in server side)
In my Controller code, the string JSON value coming from the Client code is 在我的Controller代码中,来自Client代码的字符串JSON值是
{"College":{"collegeName":"sfd","universityOrBoardName":"sdd","website":"fdd"}}
My Controller code 我的控制器代码
CollegeController.java CollegeController.java
@RequestMapping(value="/submitCol", method = RequestMethod.POST)
public String mycollege(@RequestBody String str,HttpServletRequest req)
{
Gson gson=new Gson();
Type type = new TypeToken<College>(){}.getType();
College cols=gson.fromJson(str, type);
System.out.println("College Name "+cols.getCollegeName());//HERE ITS PRINTING NULL
}
So my question is..I am sending two JSONs namely Address, College from Client side and in my controller I am trying to convert them into their respective Java Value Objects( Java Beans) . 所以我的问题是..我正在从客户端发送两个JSON,即地址,大学 ,并且在我的控制器中,我试图将它们转换为各自的Java值对象(Java Beans) 。 But I am not able to do it. 但是我做不到。 Please help. 请帮忙。
Create Class to hold both POJO's say it be RequestCommand: 创建Class来保存两个POJO都说是RequestCommand:
class RequestCommand{
private College college;
private Address address;
// follows getter and setter
}
Your Address and College POJO will automatically be binded inside RequestCommand by Spring Framework to controller method Params like below: Spring Framework会自动将您的地址和College POJO绑定到RequestCommand中,并绑定到控制器方法,如下所示:
@RequestMapping(value="/submitCol", method = RequestMethod.POST)
public String mycollege(@ModelAttribute RequestCommand command)
{
// use both of them here
command.getCollege();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.