【问题标题】:READ JSON String in servlet在 servlet 中读取 JSON 字符串
【发布时间】:2011-07-17 08:56:57
【问题描述】:

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

这里的代码是sn-p

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

【问题讨论】:

  • 为什么不创建一个包含 mydata.name、mydata.age 的 javascript 对象 mydata?那么你可以只在你的servlet中提取特定参数而不是解码json?
  • 我不能因为键值可以从一个 POST 到另一个不同
  • 你可以在你的函数中使用 JQuery 解码 json 时,fwiw。不是说应该是你的解决方案,但它会完成同样的事情。

标签: java json servlets


【解决方案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
    }
    

    【讨论】:

    • 里面的第一行 while -- >Required type:StringProvided:Object
    【解决方案3】:

    这就是我的例子。我使用 json.JSONTokener 来标记我的字符串。 (来自这里的 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

    【讨论】:

    • 知道如何解决这个问题java.lang.NoClassDefFoundError: org/json/JSONTokener
    【解决方案4】:

    如果您只想将其编组为 Map,请尝试 Jackson

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

    【讨论】:

      猜你喜欢
      • 2012-01-27
      • 2017-07-21
      • 2016-10-08
      • 2014-09-05
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多