Formato de datos JSON

I am passing the following JSON object from a .jsp page to a java servlet using JSON.stringify and JQuery.ajax():

{"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":""}]}

This is the code in my 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) {
}

In the method to which I pass jsonObj I am using jsonObj.length() to find out how many items are in jsonObj and it tells me 1, which in this case I would have expected 3. I even tried this:

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

which told me jsonObj.get("bin") was not a JSONObject. Is my data formatted incorrectly before I pass it from my .jsp or am I using the JSONObject in my java servlet incorrectly? How do I access the values in the JSONObject?

preguntado el 03 de mayo de 12 a las 21:05

It looks like 'bin' is an array, not an object. -

Um. Ok but isn't it an array of objects? -

Yes it is an array of objects. But, in your second code example, you get the array and then try to store it in an object of type JSONObject. -

You are missing a comma between the product code of the first bin. -

Thanks but that's just a typo -

1 Respuestas

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

contestado el 03 de mayo de 12 a las 21:05

This is what worked but I had to convert to JSONArray back to JSONObject back to JSONArray back to JSONObject to read all the data values. So there must be a better way to format the data so that I didn't have to convert back and forth. - iJared

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.