在servlet中读取JSON字符串 [英] READ JSON String in servlet

查看:1118
本文介绍了在servlet中读取JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将jQuery AJAX POST发布到servlet,数据采用JSON String的形式。
它成功发布但在Servlet端我需要将这些key-val对读入Session对象并存储它们。我尝试使用JSONObject类,但我无法得到它。

I am posting a jQuery AJAX POST to a servlet and the data is in the form of JSON String. Its getting posted successfully but on the Servlet side I need to read these key-val pairs into a Session Object and store them. I tried using JSONObject class but I am not able to get it.

下面是代码片段

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

在Servlet端

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
     }
}


推荐答案

你实际上并没有解析json。

You aren't actually parsing the 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
}

这篇关于在servlet中读取JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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