读取 servlet 中的 JSON 字符串

2022-09-02 09:32:03

我正在将jQuery AJAX POST发布到servlet,数据采用JSON字符串的形式。它成功发布,但在Servlet方面,我需要将这些键值对读取到会话对象中并存储它们。我尝试使用JSONObject类,但我无法得到它。

下面是代码片段

$(function(){
   $.ajax(
   {
      data: mydata,   //mydata={"name":"abc","age":"21"}
      method:POST,
      url: ../MyServlet,
      success: function(response){alert(response);
   }
});

在服务端

public doPost(HTTPServletRequest req, HTTPServletResponse res)
{
     HTTPSession session = new Session(false);
     JSONObject jObj    = new JSONObject();
     JSONObject newObj = jObj.getJSONObject(request.getParameter("mydata"));
     Enumeration eNames = newObj.keys(); //gets all the keys

     while(eNames.hasNextElement())
     {
         // Here I need to retrieve the values of the JSON string
         // and add it to the session
     }
}

答案 1

如果你使用jQuery .ajax(),你需要读取HttpRequest输入流。

    StringBuilder sb = new StringBuilder();
    BufferedReader br = request.getReader();
    String str;
    while( (str = br.readLine()) != null ){
        sb.append(str);
    }    
    JSONObject jObj = new JSONObject(sb.toString());

答案 2

您实际上并没有解析 json。

JSONObject jObj = new JSONObject(request.getParameter("mydata")); // this parses the json
Iterator it = jObj.keys(); //gets all the keys

while(it.hasNext())
{
    String key = it.next(); // get key
    Object o = jObj.get(key); // get value
    session.putValue(key, o); // store in session
}