【发布时间】:2014-05-17 05:06:49
【问题描述】:
我正在努力处理这种 JSON 到 Java 对象的转换。这是我的客户端 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;
}
这是映射到相应 JSON 的 Pojo 类。
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
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)
在我的控制器代码中,来自客户端代码的字符串 JSON 值是
{"College":{"collegeName":"sfd","universityOrBoardName":"sdd","website":"fdd"}}
我的控制器代码
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
}
所以我的问题是..我从客户端发送两个 JSON,即 Address, College,在我的控制器中,我试图将它们转换为各自的 >Java 值对象(Java Bean)。但我做不到。请帮忙。
【问题讨论】:
-
客户端不应发送外部 json 对象,即。包含
College的那个。它应该只发送名为College的 JSON 对象。 -
{"collegeName": "sfd", "universityOrBoardName":"sdd","website":"fdd"}是控制器所期望的。
标签: java json spring-mvc gson javabeans