如何在Spring控制器中获取JSON数据?

时间:2013-07-09 10:19:11

标签: java json spring jquery spring-mvc

我知道这很简单。但无法找到解决方案。

我的jQuery-ajax将是,

var json = {"message":"Message123","time":"time123","name":"test123"}

data : JSON.stringify(json),

我的Spring控制器将是,

@RequestMapping(value = "chat.html", method=RequestMethod.GET )
public @ResponseBody String getChat() {

System.out.println("Entered in to the controller ");

String name == ???
String msg == ???
String time == ???

//Process the functionality using the msg,name,time 

    return "Json String";
}

如何获取姓名,消息,时间的值。

希望我们的堆叠成员能帮助我。

2 个答案:

答案 0 :(得分:3)

var json = {"message":"Message123","time":"time123","name":"test123"}
data : JSON.stringify(json) should have a key , 

data : {json:{"message":"Message123","time":"time123","name":"test123"}},
url:/json/test

控制器

@RequestMapping(value = {"json/test"},method = RequestMethod.GET)
    @ResponseBody
    public String jsonTest(String json){
       JSONObject jsonObject = JSONObject.fromObject(json);
        String m = jsonObject.get("message").toString();
        String t = jsonObject.get("time").toString();
        String n = jsonObject.get("name").toString();
    }

我使用net.sf.json.JSONObject

答案 1 :(得分:0)

您可以使用此link ...

中的org.Json jar

然后尝试这个代码,我已经完成了我当前的项目并且工作正常且高效

 var json = {"message":"Message123","time":"time123","name":"test123"}
  $.ajax({
    type: "POST",
    url: "/chat.html",
    data: "jsonObject="+json,
    success: function(response) {
       // your success code
    },
    error: function(e) {
        // your error code
    }
});

在控制器中更改您的代码

@RequestMapping(value = "/chat.html", method=RequestMethod.POST )
public @ResponseBody String getChat(HttpServletRequest req,HttpServletResponse res) {
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(req.getParameter("jsonObject"));
    } catch(JSONException _instance) {
        // Exception Handle Message
    }

    System.out.println("Entered in to the controller ");
    String name ="" , msg = "", time = "";
    if(jsonObject.has("name")) {
       name = jsonObject.getString("name");
    }

    ... // Do it for other variables also

    //Process the functionality using the msg,name,time 

    return "Json String";
}