Java 如何解析另一个JSONArray中的JSONArray
我正在尝试解析JSONObject。 这个JSONObject中有一个JSONArray,在JSONArray中有另一个JSONArray。 我试图解析的json表单如下所示Java 如何解析另一个JSONArray中的JSONArray,java,json,org.json,Java,Json,Org.json,我正在尝试解析JSONObject。 这个JSONObject中有一个JSONArray,在JSONArray中有另一个JSONArray。 我试图解析的json表单如下所示 { "phone":"01029093199", "store_id":"1", "orders":[ { "menu_id":"
{
"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
公共类OrderApicController{
私人订单服务;
公共无效setOrderService(OrderService OrderService){
this.orderService=orderService;
}
@PostMapping(“/OrderInsert.do”)
公共void insertOrder(@RequestBody JSONObject JSONObject){
JSONParser JSONParser=新的JSONParser();
System.out.println(jsonObject);
System.out.println(jsonObject.get(“phone”);//phone가져오기 성공
System.out.println(jsonObject.get(“store\u id”);//store\u id가져오기 성공
System.out.println(“================JSONArray解析开始==============”);
ArrayList jsonArrayList=(ArrayList)jsonObject.get(“订单”);
for(int i=0;iprints{}(空JSONObject)
//System.out.println(“菜单id:+jTemp.getInt(“菜单id”);//不工作
}
}
}
显示的错误是
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.json.simple.JSONArray
此外,我正在使用这个json模块依赖项
org.json
json
20200518
我知道如果我使用System.out.println(OBJECT)
在控制台上打印一些东西,那么对象的toString()
方法被调用。因此,我尝试调用
toString()
,这给了我ClassCastException异常。错误实际上位于ArrayList jsonArrayList=(ArrayList)jsonObject.get(“orders”)代码>
您可以遍历JSONArray
并读取其属性,而不是将JSONArray
强制转换为ArrayList
。您的代码可以进行如下更改
@PostMapping(/OrderInsert.do)
公共void insertOrder(@RequestBody JSONObject JSONObject){
System.out.println(jsonObject);
System.out.println(jsonObject.get(“phone”);//phone가져오기 성공
System.out.println(jsonObject.get(“store\u id”);//store\u id가져오기 성공
System.out.println(“================JSONArray解析开始==============”);
JSONArray orders=jsonObject.getJSONArray(“orders”);
对于(int i=0;i
您错误地获取了订单。它应该存储在JSONArray中,而不是ArrayList中
更换:
ArrayList<JSONArray> jsonArrayList = (ArrayList<JSONArray>)jsonObject.get("orders");
JSONArray jsonArrayList = jsonObject.getJSONArray("orders");
现在,您可以像这样迭代JSONArray
for(int i = 0; i < jsonArrayList.length(); i++) {
System.out.println(jsonArrayList.get(i)); // SUCCESS
String temp = jsonArrayList.get(i).toJSONString();
System.out.println(temp);
}
for(int i=0;i
非常感谢您的回复。这真的很有帮助!!:)非常感谢你。我真的没想到您会解释更多关于遍历更多json
。非常感谢。