【问题标题】:JSONObject can't read attribute from existing object even though object is correctly instanced即使对象已正确实例化,JSONObject 也无法从现有对象中读取属性
【发布时间】:2020-06-22 09:50:31
【问题描述】:

即使对象正确实例化,我也无法读取 json 属性。

首先,我使用 JavaScript 从客户端发送 json:

let object = {
        firstName: document.getElementById("firstName").value,
        lastName: document.getElementById("lastName").value,
        username: document.getElementById("username").value,
        password: document.getElementById("password").value,
        email: document.getElementById("email").value,
        action: "registration"
}

let request = new XMLHttpRequest();
...

在服务器端我有代码:

req.setCharacterEncoding("UTF-8");
    JSONObject jsonObject = null;

    // String address = "/WEB-INF/pages/login.jsp";
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = req.getReader();
        while ((line = reader.readLine()) != null)
            jb.append(line);
    } catch (Exception e) {
        /* report an error */ }

    try {
        jsonObject = HTTP.toJSONObject(jb.toString());
    } catch (JSONException e) {
        // crash and burn
        throw new IOException("Error parsing JSON request string");
    }

    String action = jsonObject.getString("firstName");

jsonObject 存在,但程序抛出 org.json.JSONException: JSONObject["firstName"] not found.

我使用调试器时服务器端的对象:

【问题讨论】:

  • 查看图像(调试器)Request-URIMethod 是您的键 firstName 是键 Method 的值。如果您想获取 json 结构,请复制该 json 字符串并使用任何在线 json 格式化程序进行解析

标签: javascript java json http web


【解决方案1】:

您的jsonObject 中没有名称类似于firstName 的密钥。相反,您需要搜索Method 属性,然后从中解析firstName。首先,声明一个GetQueryMap 方法:

public static Map<String, String> GetQueryMap(String query)  
{  
    String[] params = query.split("&");  
    Map<String, String> map = new HashMap<String, String>();  
    for (String param : params)  
    {  
        String [] p=param.split("=");
        String name = p[0];  
        if(p.length>1)  {
           String value = p[1];  
           map.put(name, value);
        }  
    }  
    return map;  
}

然后像这样使用它:

String method = jsonObject.getString("Method");
Map params = GetQueryMap(method);
String firstName = (String)params.get("firstName");
String lastName = (String)params.get("lastName");

【讨论】:

    【解决方案2】:

    我认为问题在于您没有从浏览器端正确发送数据。 您是否发送了正确的 content-type 标头 (application/json)? 您是否正确序列化对象以进行发送?

    【讨论】:

      猜你喜欢
      • 2017-11-10
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多