我使用JSON.stringify和JQuery.ajax()将以下JSON对象从.jsp页面传递给java servlet:
{"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,在这种情况下我会预期3.我甚至试过这个:< / p>
JSONObject bins = jsonObj.get("bin");
bins.length();
告诉我jsonObj.get(“bin”)不是JSONObject。在我从.jsp传递数据之前,我的数据是否格式错误,或者我在java servlet中错误地使用了JSONObject?如何访问JSONObject中的值?
答案 0 :(得分:2)
JSONArray bins = jsonObj.getJSONArray("bin");
bins.length();