java 将复杂的 json 对象发送到 Spring MVC 控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25521784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send complex json object to Spring MVC controller
提问by oscar
I am trying to send a complex object to ajax controller for spring mvc search engine, with 3 variables: the current page, items per page and the search parameters. The problem is that with the declaration of the controller method does not take me the params variable as a Map.
我正在尝试将一个复杂的对象发送到 spring mvc 搜索引擎的 ajax 控制器,其中包含 3 个变量:当前页面、每页项目和搜索参数。问题是,控制器方法的声明并没有将 params 变量作为 Map。
As I can send the structure to collect on the controller 3 variables separately?
因为我可以发送结构来分别收集控制器 3 个变量?
Error:
错误:
Required Map parameter 'params' is not present
所需的地图参数“params”不存在
var dataToSend = {
'page': 1,
'itemsPerPage': 10,
'params': {
'codItem': "10",
'nameItem': "foo"
}
};
$.ajax({
url: form.attr("action"),
type: 'POST',
data: JSON.stringify(dataToSend),
dataType: 'json',
cache: false
}).success(function(data) {
callback(data);
});
public @ResponseBody HashMap<String, Object> search(@RequestParam(value="params") Map<String, String> params, @RequestParam(value = "page") int page, @RequestParam(value = "itemsPerPage") int itemsPerPage){
};
回答by Raph
To do this properly you need to use JSON library. Spring is bundled with Hymanson.
要正确执行此操作,您需要使用 JSON 库。Spring 与 Hymanson 捆绑在一起。
First you need to create class to represent your JSON.
首先,您需要创建类来表示您的 JSON。
public class MyJson {
int page;
int itemsPerPage;
Map<String, String> params;
public MyJson() {}
... getters/setters
}
You need to change $.ajax, send data like this { data : JSON.stringify(dataToSend)}, becouse parameter need, a name.
您需要更改 $.ajax,发送这样的数据 { data : JSON.stringify(dataToSend)},因为需要参数,名称。
In your controller method write this:
在您的控制器方法中这样写:
ObjectMapper mapper = new ObjectMapper();
// readValue(youStringJson, destinactionClass)
MyJson json = mapper.readValue(data, MyJson.class);
If you have getter for MyJson params field you can iterate over json.getParams() map.
如果你有 MyJson params 字段的 getter,你可以遍历 json.getParams() 映射。
回答by Raghu
/* An Alternative Solution: See if this helps::::Sample Code of java,javascript,jsp for search parameters. Search Parameter POJO will have search parameters + Pagenumber + RecordCounton the page + sortColumn in it */
public class SearchParameters implements Serializable{
/**
*
*/
private static final long serialVersionUID = 4847934022647742263L;
private Integer pageNumber;
private String sortColumn;
private Integer recordCount;
private String sortOrder;
private Long gdsProductId; // some search parameter
private Integer ruleId; // some search parameter
//getter and setters
}
/* your java controller method, which accepts the SearchParameter Object */
@RequestMapping(value = "/search", method = RequestMethod.POST)
@ResponseBody
public Map<String, GDS> search(SearchParameters parameters)
throws Exception {
// Print Parameter
logger.info("read :=" + parameters);
// your logic to be written here
}
/* Your Javascript will have the below function.
$("#searchPaginationform").serialize() will send the data for all the hidden elements of searchPaginationform in the below jsp.
form searchPaginationform will have hidden fields for the pagenumer,rows and other elements */
$.post('search.form', $("#searchPaginationform").serialize(), function (response) {
}
/* Your Jsp -- see the hiddenfield name is matching the SearchParameter instance variable -*/
<form:form id="searchPaginationform">
<input type="hidden" name="gdsProductId" id="gdsProductId" >
<input type="hidden" name="pageNumber" id="pageNumber" value=1>
<input type="hidden" name="sortColumn" id="sortColumn" value="metamap_id">
<input type="hidden" name="recordCount" id="recordCount" value=10>
<input type="hidden" name="sortOrder" id="sortOrder" value="desc">
<input type="hidden" name="ruleId" id="ruleId">
</form:form>
回答by Yagnesh Agola
You could simply inject the HttpServletRequest
into your Controller method and read the body yourself as shown below :
您可以简单地将 注入HttpServletRequest
到您的控制器方法中并自己阅读正文,如下所示:
public @ResponseBody HashMap<String, Object> search(HttpServletRequest request)
{
String params;
try
{
params = IOUtils.toString( request.getInputStream());
System.out.println(params);
}
catch (IOException e)
{
e.printStackTrace();
}
//Your return statement.
}
OutPut : {"page":1,"itemsPerPage":10,"params":{"codItem":"10","nameItem":"foo"}}
输出 : {"page":1,"itemsPerPage":10,"params":{"codItem":"10","nameItem":"foo"}}
You can read this attributes by converting this string into JSON Object by using JSON API sunch as GSON. Or create POJO that contain all your attributes define in JSON and convert your Json strig directly to POJO object.
您可以通过使用 JSON API sunk 作为GSON将此字符串转换为 JSON 对象来读取此属性。或者创建包含您在 JSON 中定义的所有属性的 POJO,并将您的 Json 字符串直接转换为 POJO 对象。
Sample Code :
示例代码:
MyClass obj = new Gson().fromJson(params, MyClass.class);
May this help you.
愿这对你有帮助。
回答by oscar
I have solved the problem as follows:
我已经解决了这个问题如下:
public class SearchRequestDto {
private String page;
private String itemsPerPage;
private MultiValueMap<String, List<String>> params;
}
@ResponseBody
public HashMap<String, Object> buscador(SearchRequestDto searchRequest)
{
}
The problem is that it works for the structure of the example, if I try to pick up the form parameters, sends me not as a json:
问题是它适用于示例的结构,如果我尝试获取表单参数,则不会将我作为 json 发送给我:
$.ajax({
url: form.attr("action"),
type: 'POST',
data: {
'params': form.serialize(),
'page': start,
'itemsPerPage': end
},
dataType: 'json',
cache: false
}).success(function(data) {
callback(data);
});
Result:
结果:
itemsPerPage 5
page 1
params codItem=asdfasdf&namItem=asdfasdfasdf&tipItem=1000600&tipItem=1000492&public=on&private=on&provinceItem=15&munItem=262&munItem=270&munItem=276&capItem=123123
And serializeArray():
和 serializeArray():
itemsPerPage 5 page 1
项目每页 5 页 1
params [10] [name] munItem
params [10] [value] 270
params [11] [name] munItem
params [11] [value] 276
params [13] [name] capItem
params [13] [value] 123123
params [2] [name] codItem
params [2] [value] asdfasdf
params [3] [name] nameItem
params [3] [value] asdfasdfasdf
params [4] [name] tipItem
params [4] [value] 1000600
params [5] [name] tipItem
params [5] [value] 1000492
params [6] [name] public
params [6] [value] on
params [7] [name] private
params [7] [value] on
params [8] [name] provinceItem
params [8] [value] 15
params [9] [name] munItem
params [9] [value] 262
As I can send it as in the structure of dataToSend? the only way is to go through the parameters?
因为我可以像 dataToSend 的结构一样发送它?唯一的方法是通过参数?
回答by Stupidfrog
My enviroment: AngularJs, SpringMVC, Gson jsonobject
我的环境:AngularJs、SpringMVC、Gson jsonobject
Usually if i send a complex json object from font end to back end, i will do a generic way like below to handle it.
通常,如果我从字体端向后端发送一个复杂的 json 对象,我将使用如下的通用方法来处理它。
first:
第一的:
$http({
method: 'POST',
url: contextPath+"/voice/submitWrapupForm",
dataType: 'json',
data: $.param({
content : angular.toJson( { array:$(form).serializeArray() })
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }
).success(function (data, status) {
console.log(data);
});
i use angularJs to submit a formatted json string, i believe using jquery ajax will be the same, just need to be sure that data u sent is json formatted string. https://docs.angularjs.org/api/ng/function/angular.toJson
我使用 angularJs 提交格式化的 json 字符串,我相信使用 jquery ajax 将是相同的,只需要确保您发送的数据是 json 格式的字符串。 https://docs.angularjs.org/api/ng/function/angular.toJson
second:
第二:
@RequestMapping(value = "/submitForm", method = RequestMethod.POST,headers = "Accept=application/json")
public @ResponseBody String submitForm(String content) {
JsonObject j = new Gson().fromJson(content ,JsonElement.class).getAsJsonObject();
return j.toString();
}
u can watch the json content is pass to mvc controller, and in controller u can use Gson to convert and to json object.
您可以观看 json 内容传递给 mvc 控制器,并且在控制器中您可以使用 Gson 转换并转换为 json 对象。