Подтвердить что ты не робот

READ JSON Строка в сервлете

Я отправляю jQuery AJAX POST для сервлета, и данные находятся в форме строки JSON. Его получение успешно опубликовано, но на стороне сервлета мне нужно прочитать эти пары ключ-вал в объект сеанса и сохранить их. Я попытался использовать класс JSONObject, но я не могу его получить.

Вот фрагмент кода

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

На стороне сервлета

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

Ответ 1

На самом деле вы не разбираете 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

если вы используете 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());

Ответ 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

Ответ 4

Если вы просто хотите маршалировать его на карту, попробуйте Jackson.

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