我正在获取一个JSON对象,然后将其转换为数组并尝试访问属性或值,但由于出现The type of the expression must be an array type but it resolved to JSONArray
而出错
我必须将JSON数据保存到我的数据库中,这就是为什么我要全部获取数组中的值
我的代码
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Scanner scanner = new Scanner(request.getInputStream());
String imageData = scanner.nextLine();
System.out.println(imageData);
JSONObject jsonObj = new JSONObject(imageData);
JSONArray jsonArray = jsonObj.getJSONArray("ImageData");
JSONObject innerObj = new JSONObject(jsonArray[0]); // this one is throwing error
// eror is `The type of the expression must be an array type but it resolved to JSONArray`
String counter = innerObj.getString("Counter");
String name = innerObj.getString("Name");
String isActive = innerObj.getString("IsActive");
System.out.println(counter);
}
System.out.println(imageData); it prints -->
{"ImageData":[{"Counter":"Counter A","Name":"CountA1.jpg","IsActive":"Y"},{"Counter":"Counter A","Name":"CountA2.jpg","IsActive":"Y"}]}
System.out.println(jsonArray);这个打印->
[{"Counter":"Counter A","IsActive":"Y","Name":"CountA1.jpg"},{"Counter":"Counter A","IsActive":"Y","Name":"CountA2.jpg"}]
我已经在代码中注释了我遇到错误的行
答案 0 :(得分:1)
答案 1 :(得分:0)
您不能像jsonArray [0]一样在JSONArray上添加方括号,而必须使用jsonArray.getJSONObject(“ index”);