【发布时间】:2020-08-14 05:53:57
【问题描述】:
我正在尝试解析 JSONObject。 这个 JSONObject 中有一个 JSONArray,它在 JSONArray 中还有另一个 JSONArray。 我试图解析的 json 形式如下。
{
"phone":"01029093199",
"store_id":"1",
"orders":[
{
"menu_id":"4",
"menu_defaultprice":"1500",
"extraorders":[
{
"extra_id":"1",
"extra_price":"0",
"extra_count":"1"
},
{
"extra_id":"38",
"extra_price":"300",
"extra_count":"2"
}
]
},
{
"menu_id":"4",
"menu_defaultprice":"1500",
"extraorders":[
{
"extra_id":"2",
"extra_price":"0",
"extra_count":"1"
},
{
"extra_id":"19",
"extra_price":"500",
"extra_count":"1"
}
]
},
{
"menu_id":"6",
"menu_defaultprice":"2000",
"extraorders":[
{
"extra_id":"6",
"extra_price":"0",
"extra_count":"1"
},
{
"extra_id":"21",
"extra_price":"500",
"extra_count":"1"
},
{
"extra_id":"41",
"extra_price":"300",
"extra_count":"1"
}
]
}
]
}
下面的代码是我之前尝试过的。
@RestController
public class OrderApiController {
private OrderService orderService;
public void setOrderService(OrderService orderService) {
this.orderService = orderService;
}
@PostMapping("/OrderInsert.do")
public void insertOrder(@RequestBody JSONObject jsonObject) {
JSONParser jsonParser = new JSONParser();
System.out.println(jsonObject);
System.out.println(jsonObject.get("phone")); // phone 가져오기 성공
System.out.println(jsonObject.get("store_id")); // store_id 가져오기 성공
System.out.println("==========JSONArray Parsing start=========");
ArrayList<JSONArray> jsonArrayList = (ArrayList<JSONArray>)jsonObject.get("orders");
for(int i = 0; i < jsonArrayList.size(); i++) {
System.out.println(jsonArrayList.get(i)); // SUCCESS
String temp = jsonArrayList.get(i).toJSONString(); // WHERE ERROR HAPPENS
System.out.println(temp);
// Tried below code to remove "[", "]" from JSONArray, but not working.
// Error message was same as the message shown from line 37.
//String jsonString = temp.substring(1, temp.length()-1);
//System.out.println(jsonString);
// org.json.JSONObject jTemp = new org.json.JSONObject(jsonArrayList.get(i));
// System.out.println(jTemp); --> prints {} (empty JSONObject)
// System.out.println("menu_id : " + jTemp.getInt("menu_id")); // Not Working
}
}
}
显示的错误是..
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.json.simple.JSONArray
另外,我正在使用这个 json 模块依赖项。
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20200518</version>
</dependency>
我知道如果我在控制台上使用System.out.println(OBJECT) 打印一些东西,那么对象的toString()
方法被调用。所以我尝试调用 toString() ,这给了我 ClassCastException 异常。
【问题讨论】: