Javascript JSONObject可以';即使对象已正确实例化,也无法从现有对象读取属性
即使对象正确实例化,我在读取json属性时也有问题 首先,我使用JavaScript从客户端发送json:Javascript JSONObject可以';即使对象已正确实例化,也无法从现有对象读取属性,javascript,java,json,http,web,Javascript,Java,Json,Http,Web,即使对象正确实例化,我在读取json属性时也有问题 首先,我使用JavaScript从客户端发送json: let object = { firstName: document.getElementById("firstName").value, lastName: document.getElementById("lastName").value, username: document.getElementById("username").val
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”]未找到
使用调试器时服务器端的对象:
在您的
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;
}
我认为问题在于您没有从浏览器端正确发送数据。 您是否发送了正确的
内容类型
标题(application/json
)?
是否正确序列化对象以发送?查看图像(调试器)请求URI
和方法
是否为键firstName是键方法
的值。如果您想获取json结构,请复制该json字符串并使用任何json格式化程序联机解析
String method = jsonObject.getString("Method");
Map params = GetQueryMap(method);
String firstName = (String)params.get("firstName");
String lastName = (String)params.get("lastName");