我传递了以下JSON对象从.JSP页面透过JSON.stringify和JQuery.ajax()一个Java servlet:JSON数据格式
{"bin":[{"binId":"0","binDetails":[{"productCode":"AU192","qty":"4"},{"productCode":"NE823","qty":"8"}],"comments":"store pickup"},{"binId":"1","binDetails":[{"productCode":"AF634","qty":"2"}],"comments":""},{"binId":"2","binDetails":[{"productCode":"QB187","qty":"3"}],"comments":"international shipping"},{"binId":"3","binDetails":[{"productCode":"AF634","qty":"2"},{"productCode":"QB187","qty":"2"}],"comments":""}]}
这是我的Java Servlet代码:
StringBuffer strBuffer = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null){
strBuffer.append(line);
}
} catch (Exception e) {
}
try {
JSONObject jsonObj = new JSONObject(new JSONTokener(strBuffer.toString()));
// I call a method here and pass jsonObj
} catch (Exception e) {
}
在该方法中,我通过jsonObj我使用jsonObj.length()来找出有多少项目是jsonObj,它告诉我1,在这种情况下,我本来期望我甚至试过这个:
JSONObject bins = jsonObj.get("bin");
bins.length();
告诉我jsonObj.get(“bin”)不是JSONObject。我的数据在我的.jsp传递之前格式不正确,还是我在我的java servlet中错误地使用了JSONObject?我如何访问JSONObject中的值?
它看起来像'bin'是一个数组,而不是一个对象。 – Quantastical
嗯。好的,但不是一个对象数组? – iJared
是的,它是一个对象数组。但是,在第二个代码示例中,获取数组,然后尝试将其存储在JSONObject类型的对象中。 – Quantastical