将 JSON 数据传递给 Spring MVC 控制器 [英] passing JSON data to a Spring MVC controller

查看:45
本文介绍了将 JSON 数据传递给 Spring MVC 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向 Spring MVC 控制器发送一个 JSON 字符串.但我不需要有任何表单绑定,我只需要向控制器类发送一个普通的 JSON 数据.我正在像下面的代码一样对控制器方法进行 jQuery AJAX 调用.

I need to send a JSON string to Spring MVC controller.But I do not have any form bindings to it , I just need to send a plain JSON data to Controller class.I am making jQuery AJAX call to the Controller method like the below code.

$.ajax ({
    url: "./save",
    type: "POST",
    data: JSON.stringify(array),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(){
        alert("success ");
    }
});

但是如何在 Controller 方法中检索它?(注意:它只是普通的 JSON 数据,而不是表单提交).

But how do I retrieve it in the Controller method?(Note: It is just plain JSON data and not a form submission).

推荐答案

添加以下依赖

<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.7</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.7</version>
</dependency>

修改请求如下

$.ajax({ 
    url:urlName,    
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser          
    processData:false, //To avoid making query String instead of JSON
    success: function(resposeJsonObject){
        // Success Message Handler
    }
});

控制器端

@RequestMapping(value = urlPattern , method = RequestMethod.POST)
public @ResponseBody Person save(@RequestBody Person jsonString) {

   Person person=personService.savedata(jsonString);
   return person;
}

@RequestBody - 将 Json 对象转换为 Java
@ResponseBody- 将 Java 对象转换为 json

@RequestBody - Covert Json object to java
@ResponseBody- convert Java object to json

这篇关于将 JSON 数据传递给 Spring MVC 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆