---
title: "spring mvc 接收json"
author: "ainn2006"
date: "2012-09-13T18:26:36Z"
tags: []
categories: ["非技术"]
slug: "spring-mvc-json"
draft: false
lastmod: "2012-09-13T18:26:36Z"
id: 1678085
url: "https://ainn2006.iteye.com/blog/1678085"
---

 接收JSON
使用 @RequestBody 注解前台只需要向 Controller 提交一段符合格式的 JSON，Spring 会自动将其拼装成 bean。
1)在上面的项目中使用第一种方式处理返回JSON的基础上，增加如下方法：
Java代码  收藏代码

    @RequestMapping(value="/add",method=RequestMethod.POST, headers = {"content-type=application/json","content-type=application/xml"})  
    @ResponseBody  
    public Object addUser(@RequestBody User user)  
    {  
        System.out.println(user.getName() + " " + user.getAge());  
        return new HashMap<String, String>().put("success", "true");  
    }  

 这里的POJO如下：
Java代码  收藏代码

    public class User {  
        private String name;  
        private String age;  
      
        //getter setter  
    }  

 
2）而在前台，我们可以用 jQuery 来处理 JSON。从这里，我得到了一个 jQuery 的插件，可以将一个表单的数据返回成JSON对象：
Js代码  收藏代码

    $.fn.serializeObject = function(){  
        var o = {};  
        var a = this.serializeArray();  
        $.each(a, function(){  
            if (o[this.name]) {  
                if (!o[this.name].push) {  
                    o[this.name] = [o[this.name]];  
                }  
                o[this.name].push(this.value || '');  
            }  
            else {  
                o[this.name] = this.value || '';  
            }  
        });  
        return o;  
    };  

 
   以下是使用 jQuery 接收、发送 JSON 的代码：
Js代码  收藏代码

    $(document).ready(function(){  
        jQuery.ajax({  
            type: 'GET',  
            contentType: 'application/json',  
            url: 'jsonfeed.do',  
            dataType: 'json',  
            success: function(data){  
                if (data && data.status == "0") {  
                    $.each(data.data, function(i, item){  
                        $('#info').append("姓名：" + item.name +"，年龄：" +item.age);  
                    });  
                }  
            },  
            error: function(){  
                alert("error")  
            }  
        });  
        $("#submit").click(function(){  
            var jsonuserinfo = $.toJSON($('#form').serializeObject());  
            jQuery.ajax({  
                type: 'POST',  
                contentType: 'application/json',  
                url: 'add.do',  
                data: jsonuserinfo,  
                dataType: 'json',  
                success: function(data){  
                    alert("新增成功！");  
                },  
                error: function(){  
                    alert("error")  
                }  
            });  
        });  
    });  

 
但是似乎用Spring这套东西真是个麻烦的事情，相对Jersey对RESTful的实现来看，确实有很多不简洁的地方。

 