JSON 数据格式设置



我正在使用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。 我什至尝试过这个:

JSONObject bins = jsonObj.get("bin");
bins.length();

它告诉我jsonObj.get("bin")不是JSONObject。 在我从.jsp传递数据之前,我的数据的格式是否不正确,或者我在java servlet中使用了不正确的JSONObject? 如何访问 JSON 中的值?

JSONArray bins = jsonObj.getJSONArray("bin");
bins.length();

最新更新