java - 如何使用ajax读取json到servlet

标签 java

我需要您的帮助才能将 JSON 从 JQuery AJAX 读取到我的 servlet。 我想解析来自 ajax 调用的内部数据到 jsonObject。

我的代码获取 facebook 用户信息并将相关数据传递给 json,然后将 AJAX 调用发送到 servlet。 如何在 servlet 请求中读取这些参数?

 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
    });

如何使用 HttpServletRequest 解析 servlet 中的“jsonUserInfo”对象? 我正在使用 JSON-org jar。

谢谢, 伊多

最佳答案

我不知道 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));

关于java - 如何使用ajax读取json到servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5687250/

相关文章:

java - 如何使用 Java 找到一年中第 # 周的月份的所有周数?

java - Spring注释@Validated在kotlin类中不起作用,相同的java代码可以工作

显然存在 java.lang.NoSuchMethodError

java - BigDecimal 行为的差异

java - 如何在junit中建立测试用例?

java - 如何将上下文从 MainActivity 传递到 Android 中的另一个类?

java - 两个相同的接口(interface) : Yet, 不能转换为另一个吗?

java - Android中如何管理字符串资源

java - BlockingQueue 在调用之前不处理中断

java - 解码字符串内的 ASCII 字符