4

我知道这是一个简单的。但找不到解决办法。

我的 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";
}

如何获取名称、消息、时间的值。

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

4

2 回答 2

4
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

于 2013-07-11T02:09:41.713 回答
0

您可以从此链接使用 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";
}
于 2014-02-17T13:14:35.083 回答