即使对象已正确实例化,JSONObject也无法从现有对象读取属性

时间:2020-03-10 13:28:14

标签: javascript java json http web

即使对象已正确实例化,我也无法读取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”]。

使用调试器时服务器端的对象: enter image description here

2 个答案:

答案 0 :(得分:1)

您的firstName中没有名称为jsonObject的密钥。相反,您需要搜索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");

答案 1 :(得分:0)

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

相关问题