如何解析嵌套在另一个JSONArray中的JSONArray

huangapple go评论96阅读模式
英文:

How to parse JSONArray which is in another 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"
                }
            ]
        }
    ]
}

您提供的Java代码用于解析JSON数据,以下是相关部分的翻译:

@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")); // 获取电话号码成功
        System.out.println(jsonObject.get("store_id"));  // 获取商店ID成功
        System.out.println("==========开始解析JSONArray=========");
        ArrayList<JSONArray> jsonArrayList = (ArrayList<JSONArray>)jsonObject.get("orders");
        for(int i = 0; i < jsonArrayList.size(); i++) {
            System.out.println(jsonArrayList.get(i));  // 成功

            String temp = jsonArrayList.get(i).toJSONString(); // 错误发生的地方
            System.out.println(temp);

            // 尝试下面的代码来移除JSONArray中的 "[" 和 "]",但不起作用。
            // 错误消息与第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);  --&gt; 打印 {} (空的JSONObject)
            // System.out.println("menu_id : " + jTemp.getInt("menu_id")); // 不起作用
        }
    }
}

错误信息显示为:

java.lang.ClassCastException: java.util.LinkedHashMap无法强制转换为org.json.simple.JSONArray

此外,您正在使用的JSON模块依赖关系如下:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20200518</version>
</dependency>

我明白如果您使用System.out.println(OBJECT)在控制台上打印对象,那么将调用对象的toString()方法。因此,您尝试调用toString()方法,但出现了ClassCastException异常。

英文:

I am trying to parse a JSONObject.
This JSONObject has a JSONArray in it, and it has another JSONArray inside of JSONArray.
The json form that I am trying to parse is as below.

{
    &quot;phone&quot;:&quot;01029093199&quot;,
    &quot;store_id&quot;:&quot;1&quot;,
    &quot;orders&quot;:[
        {
            &quot;menu_id&quot;:&quot;4&quot;,
            &quot;menu_defaultprice&quot;:&quot;1500&quot;,
            &quot;extraorders&quot;:[
                {
                    &quot;extra_id&quot;:&quot;1&quot;,
                    &quot;extra_price&quot;:&quot;0&quot;,
                    &quot;extra_count&quot;:&quot;1&quot;
                },
                {
                    &quot;extra_id&quot;:&quot;38&quot;,
                    &quot;extra_price&quot;:&quot;300&quot;,
                    &quot;extra_count&quot;:&quot;2&quot;
                }
            ]
        },
        {
            &quot;menu_id&quot;:&quot;4&quot;,
            &quot;menu_defaultprice&quot;:&quot;1500&quot;,
            &quot;extraorders&quot;:[
                {
                    &quot;extra_id&quot;:&quot;2&quot;,
                    &quot;extra_price&quot;:&quot;0&quot;,
                    &quot;extra_count&quot;:&quot;1&quot;
                },
                {
                    &quot;extra_id&quot;:&quot;19&quot;,
                    &quot;extra_price&quot;:&quot;500&quot;,
                    &quot;extra_count&quot;:&quot;1&quot;
                }
            ]
        },
        {
            &quot;menu_id&quot;:&quot;6&quot;,
            &quot;menu_defaultprice&quot;:&quot;2000&quot;,
            &quot;extraorders&quot;:[
                {
                    &quot;extra_id&quot;:&quot;6&quot;,
                    &quot;extra_price&quot;:&quot;0&quot;,
                    &quot;extra_count&quot;:&quot;1&quot;
                },
                {
                    &quot;extra_id&quot;:&quot;21&quot;,
                    &quot;extra_price&quot;:&quot;500&quot;,
                    &quot;extra_count&quot;:&quot;1&quot;
                },
                {
                    &quot;extra_id&quot;:&quot;41&quot;,
                    &quot;extra_price&quot;:&quot;300&quot;,
                    &quot;extra_count&quot;:&quot;1&quot;
                }
            ]
        }
    ]
}

The code below is what I have tried before.

@RestController
public class OrderApiController {

    private OrderService orderService;

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    @PostMapping(&quot;/OrderInsert.do&quot;)
    public void insertOrder(@RequestBody JSONObject jsonObject) {
        JSONParser jsonParser = new JSONParser();

        System.out.println(jsonObject);
        System.out.println(jsonObject.get(&quot;phone&quot;)); // phone 가져오기 성공
        System.out.println(jsonObject.get(&quot;store_id&quot;));  // store_id 가져오기 성공
        System.out.println(&quot;==========JSONArray Parsing start=========&quot;);
        ArrayList&lt;JSONArray&gt; jsonArrayList = (ArrayList&lt;JSONArray&gt;)jsonObject.get(&quot;orders&quot;);
        for(int i = 0; i &lt; 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 &quot;[&quot;, &quot;]&quot; 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);  --&gt; prints {} (empty JSONObject)
            // System.out.println(&quot;menu_id : &quot; + jTemp.getInt(&quot;menu_id&quot;)); // Not Working
        }
    }
}

The error shown is ..

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.json.simple.JSONArray

Additionally, I am using this json module dependency.

&lt;dependency&gt;
    &lt;groupId&gt;org.json&lt;/groupId&gt;
    &lt;artifactId&gt;json&lt;/artifactId&gt;
    &lt;version&gt;20200518&lt;/version&gt;
&lt;/dependency&gt;

I knew that if I print something on console using System.out.println(OBJECT), the OBJECT's toString()
method is called. So I tried to call toString() , and that gave me the ClassCastException exception.

答案1

得分: 1

以下是翻译的部分:

错误实际上在ArrayList&lt;JSONArray&gt; jsonArrayList = (ArrayList&lt;JSONArray&gt;)jsonObject.get(&quot;orders&quot;);这一行。

您可以不将JSONArray强制转换为ArrayList,而是遍历JSONArray并读取其属性。您的代码可以修改为类似以下方式。

@PostMapping("/OrderInsert.do")
public void insertOrder(@RequestBody JSONObject jsonObject) {
    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=========");
    JSONArray orders = jsonObject.getJSONArray("orders");
    for(int i = 0; i < orders.length(); i++) {
        System.out.println(orders.get(i));  // 成功

        String temp = orders.get(i).toString();
        System.out.println(temp);

        // 进一步遍历json
        JSONObject order = orders.getJSONObject(i);
        System.out.println(order.get("menu_defaultprice"));
        System.out.println(order.get("menu_id"));
        JSONArray extraorders = order.getJSONArray("extraorders");
        for(int j = 0; j < extraorders.length(); j++) {
            JSONObject extraOrder = extraorders.getJSONObject(j);
            System.out.println(extraOrder.get("extra_id"));
            System.out.println(extraOrder.get("extra_price"));
            System.out.println(extraOrder.get("extra_count"));
        }
    }
}
英文:

Error is in fact at ArrayList&lt;JSONArray&gt; jsonArrayList = (ArrayList&lt;JSONArray&gt;)jsonObject.get(&quot;orders&quot;);

Instead of casting JSONArray to ArrayList, you can traverse JSONArray and read its attributes. Your code can be changed something like.

    @PostMapping(&quot;/OrderInsert.do&quot;)
    public void insertOrder(@RequestBody JSONObject jsonObject) {
        System.out.println(jsonObject);
        System.out.println(jsonObject.get(&quot;phone&quot;)); // phone 가져오기 성공
        System.out.println(jsonObject.get(&quot;store_id&quot;));  // store_id 가져오기 성공
        System.out.println(&quot;==========JSONArray Parsing start=========&quot;);
        JSONArray orders = jsonObject.getJSONArray(&quot;orders&quot;);
        for(int i = 0; i &lt; orders.length(); i++) {
            System.out.println(orders.get(i));  // SUCCESS

            String temp = orders.get(i).toString();
            System.out.println(temp);

            // Travserse further json
            JSONObject order = orders.getJSONObject(i);
            System.out.println(order.get(&quot;menu_defaultprice&quot;));
            System.out.println(order.get(&quot;menu_id&quot;));
            JSONArray extraorders = order.getJSONArray(&quot;extraorders&quot;);
            for(int j = 0; j &lt; extraorders.length(); j++) {
                JSONObject extraOrder = extraorders.getJSONObject(j);
                System.out.println(extraOrder.get(&quot;extra_id&quot;));
                System.out.println(extraOrder.get(&quot;extra_price&quot;));
                System.out.println(extraOrder.get(&quot;extra_count&quot;));
            }
        }
    }

答案2

得分: 1

你正在错误地获取orders。它应该存储在JSONArray中,而不是ArrayList<JSONArray>。

替换

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);
}
英文:

You are incorrectly fetching the orders. It should be stored in JSONArray, and NOT ArrayList<JSONArray>

Replace:

ArrayList&lt;JSONArray&gt; jsonArrayList = (ArrayList&lt;JSONArray&gt;)jsonObject.get(&quot;orders&quot;);

With:

JSONArray jsonArrayList = jsonObject.getJSONArray(&quot;orders&quot;);

Now, you can iterate JSONArray like this

for(int i = 0; i &lt; jsonArrayList.length(); i++) {
System.out.println(jsonArrayList.get(i));  // SUCCESS
String temp = jsonArrayList.get(i).toJSONString();
System.out.println(temp);
}

huangapple
  • 本文由 发表于 2020年8月14日 13:53:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63407292.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定