我得到一个 JSON 对象,然后将其转换为数组并尝试访问属性或值,但收到错误 表达式的类型必须是数组类型,但它解析为 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":[{"计数器":"计数器 A","名称":"CountA1.jpg","IsActive":"Y"},{"计数器":"计数器 A","名称":"CountA2.jpg","IsActive":"Y"}]}
System.out.println(jsonArray);这个打印 -->
[{"计数器":"计数器 A","IsActive":"Y","名称":"CountA1.jpg"},{"计数器":"计数器 A","IsActive": "Y","名称":"CountA2.jpg"}]
我已经评论了代码中出现错误的行
最佳答案
使用getJSONObject方法
JSONObject innerObj = jsonArray.getJSONObject(0);
Returns the value at index if it exists and is a JSONObject.
关于java - 表达式的类型必须是数组类型,但它解析为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56542414/