как читать ajax с json для сервлета

Мне нужна ваша помощь, чтобы прочитать JSON из JQuery AJAX в мой сервлет. Я хочу проанализировать внутренние данные из ajax-вызова jsonObject.

Мой код получает информацию о пользователе facebook и передает соответствующие данные в json, а затем отправляет вызов AJAX на сервлет. Как мне прочитать эти параметры в моем запросе сервлета?

 var jsonUserInfo = [];
      jsonUserInfo.push({"id"           :   (response["id"]         ? response["id"]            : "wnull")}); 
      jsonUserInfo.push({"first_name"   :   (response["first_name"] ? response["first_name"]    : "wnull")});  
      jsonUserInfo.push({"last_name"    :   (response["last_name"]  ? response["last_name"]     : "wnull")});  
      jsonUserInfo.push({"username" :   (response["username"]   ? response["username"]      : "wnull")});  
      jsonUserInfo.push({"birthday"     :   (response["birthday"]   ? response["birthday"]      : "wnull")});  
      jsonUserInfo.push({"gender"       :   (response["gender"]     ? response["gender"]        : "wnull")});  
      jsonUserInfo.push({"relationship_status": (response["relationship_status"] ? response["relationship_status"] : "wnull")});  
      jsonUserInfo.push({"timezone" :   (response["timezone"]   ? response["timezone"]      : "wnull")});  
      jsonUserInfo.push({"locale"   :   (response["locale"]     ? response["locale"]        : "wnull")});  
      jsonUserInfo.push({"verified"     :   (response["verified"]   ? response["verified"]      : "wnull")});  
      jsonUserInfo.push({"updated_time":    (response["updated_time"] ? response["updated_time"]: "wnull")});  
      jsonUserInfo.push({"interested_in": (response["interested_in"] ? response["interested_in"] : [])});  
      jsonUserInfo.push({"meeting_for":     (response["meeting_for"] ? response["meeting_for"]  : [])});

И вот мой вызов ajax:

$.ajax({ url: "MainController",
     type:"POST",
     data: ({   "action"    : "setFacebookUserInfo",
                "userInfo"  : jsonUserInfo,
                "servlet"   : "UserProfile"
            }),
     dataType:"json",
     contentType: "application/x-www-form-urlencoded; charset=UTF-8",
     success: function(data){
        alert("here");
     },
     cache: true,
     ifModified: true
    });

Как мне проанализировать объект jsonUserInfo в моем сервлете с помощью HttpServletRequest? Я использую банку JSON-org.

Спасибо, Идо


person ido    schedule 16.04.2011    source источник


Ответы (1)


Я не знаю о JSON-org, но с JSON-simple вы просто сделать JSONObject jsonobject = (JSONObject)(new JSONParser().parse(jsonstring)); или JSONArray jsonarray = (JSONArray)(new JSONParser().parse(jsonstring));

В org.json это делается следующим образом: JSONObject jsonobject = new JSONObject(new JSONTokener(jsonstring)); или JSONArray jsonarray = new JSONArray(new JSONTokener(jsonstring));

person Thomas    schedule 16.04.2011
comment
Во-первых, Томас, спасибо за ваш ответ. Как получить данные jsonstring, если я использую: JSONObject jsonobject = new JSONObject(new JSONTokener(request.getParameter(userInfo))); я получаю сообщение об ошибке. - person ido; 16.04.2011
comment
Я получаю исключение в отношении нулевого объекта: java.lang.NullPointerException в org.json.JSONTokener.more(JSONTokener.java:98) в org.json.JSONTokener.next(JSONTokener.java:108) в org.json.JSONTokener. nextClean(JSONTokener.java:162) в org.json.JSONObject.‹init›(JSONObject.java:178) - person ido; 16.04.2011
comment
Ну, я не эксперт по JavaScript, но я предполагаю, что проблема либо в поле contentType в вашем вызове, либо вы должны назвать параметр userInfo вместо "userInfo". - person Thomas; 16.04.2011