在servlet中读取JSON字符串

时间:2011-03-17 12:23:21

标签: java json servlets

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

下面是代码段

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

4 个答案:

答案 0 :(得分:17)

如果使用jQuery .ajax(),则需要读取Http Request输入流

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

答案 1 :(得分:15)

你实际上并没有解析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
}

答案 2 :(得分:2)

所以这是我的榜样。我使用json.JSONTokener来标记我的String。 (来自这里的Json-Java API https://github.com/douglascrockford/JSON-java

String sJsonString = "{\"name\":\"abc\",\"age\":\"21\"}";
// Using JSONTokener to tokenize the String. This will create json Object or json Array 
// depending on the type cast.
json.JSONObject jsonObject = (json.JSONObject) new json.JSONTokener(sJsonString).nextValue();

Iterator iterKey = jsonObject.keys(); // create the iterator for the json object.
while(iterKey.hasNext()) {
    String jsonKey = (String)iterKey.next(); //retrieve every key ex: name, age
    String jsonValue = jsonObject.getString(jsonKey); //use key to retrieve value from 

    //This is a json object and will display the key value pair.

    System.out.println(jsonKey  + " --> " + jsonValue  );
}

输出:
年龄 - > 21个
名称 - > ABC

答案 3 :(得分:0)

如果您只想将其编组到地图中,请尝试Jackson

ObjectMapper mapper = new ObjectMapper();
...
Map<String, Object> data = mapper.readValue(request.getParameter("mydata"), Map.class);