2011-03-17 69 views
20

我正在发布一个jQuery AJAX POST到一个servlet并且数据是JSON字符串的形式。 它成功发布,但在Servlet端,我需要将这些key-val对读入会话对象并存储它们。我尝试使用JSONObject类,但我无法得到它。在servlet中读取JSON字符串

继承人的代码片断

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

为什么不创建一个JavaScript对象mydata,其中包含mydata.name,mydata.age?那么你可以只是拉你的servlet的具体参数,而不是解码json? – dmcnelis 2011-03-17 12:30:23

+0

我不能'因为key-val可以从POST到另一个不同 – sv1 2011-03-17 12:37:52

+0

你可以在你的函数中使用JQuery解码json时,fwiw。不是说应该是你的解决方案,但它会完成同样的事情。 – dmcnelis 2011-03-17 12:46:51

回答

14

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

如果你只是想将它封送成地图,然后尝试Jackson

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

所以这里是我的例子。我用json.JSONTokener来标记我的字符串。 (从这里https://github.com/douglascrockford/JSON-java JSON-的Java API)

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

如果使用
17

jQuery的阿贾克斯(),您需要读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());