【发布时间】:2019-10-25 19:11:59
【问题描述】:
我正在获取一个 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"}]
我已经在我的代码中注释了出现错误的行
【问题讨论】: