Czytaj ciąg JSON w servlet

Zamieszczam post jQuery AJAX do servletu, a dane są w postaci JSON String. Its getting posted successfully ale po stronie Servlet muszę odczytać te pary key-val w obiekcie sesji i zapisać je. Próbowałem użyć klasy JSONObject, ale nie jestem w stanie go uzyskać.

Heres the code snippet

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

Po stronie Servleta

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
     }
}
Author: Boro, 2011-03-17

4 answers

Nie analizujesz 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
}
 15
Author: Robby Pond,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-17 13:04:23

Jeśli używasz jQuery .ajax (), musisz odczytać strumień wejściowy 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());
 17
Author: J. Moreno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-20 18:41:16

Oto mój przykład. Użyłem json.JSONTokener to tokenize my String. (Json-Java API from here 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  );
}

Wyjście:
wiek-- > 21
nazwa-- > abc

 2
Author: kensen john,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-17 13:51:28

Jeśli chcesz po prostu umieścić go na mapie, spróbuj } Jackson .

ObjectMapper mapper = new ObjectMapper();
...
Map<String, Object> data = mapper.readValue(request.getParameter("mydata"), Map.class);
 0
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-17 12:44:02