即使对象已正确实例化,我也无法读取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”]。
答案 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
)?
您是否正确序列化了对象以进行发送?