// 通过获取输入流来读取buffer的数据 BufferedInputStream bis = new BufferedInputStream(request.getInputStream()); ByteArrayOutputStream buf = new ByteArrayOutputStream(); int result = bis.read(); while(result != -1) { buf.write((byte) result); result = bis.read(); } String str = buf.toString();
/* 或 ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { result.write(buffer, 0, length); } String str = result.toString(StandardCharsets.UTF_8.name()); */
JSONObject jsonObject = new JSONObject(str); // 解析简单数据 String name = (String)jsonObject.get("name"); Integer age = (Integer)jsonObject.get("age");
System.out.println(name + " " + age);
// 解析对象数组 JSONArray songArr = (JSONArray)jsonObject.get("songs"); for (int i = 0; i < songArr.length(); i++) { JSONObject song = (JSONObject)songArr.get(i); String songname = (String)song.get("name"); String singer = (String)song.get("singer"); System.out.println(songname + " " + singer); } }