【问题标题】:How to do Parsing JSON string in Java with nested arrays如何使用嵌套数组在 Java 中解析 JSON 字符串
【发布时间】:2021-06-24 04:01:57
【问题描述】:

从类似的问题开始, Nested JSON Array in Java 我有一个有点奇怪的 json 作为 REST api(POST) 调用的响应。我需要在每个items 数组元素中找出sub_items 数组的idname

我尝试了下面给出的错误,例如

org.json.JSONException: JSONObject["items.sub_items"] 未找到。

我也尝试将“sub_items”作为参数,但没有。我正在使用 GSON。没办法用别人。

final JSONObject jsonObj = new JSONObject(JSON_STRING);
final JSONArray subItems = jsonObj.getJSONArray("items.sub_items");
final int       n       = subItems.length();
for (int i = 0; i < n; ++i) {
    final JSONObject subI= subItems.getJSONObject(i);
    System.out.println("id="+subI.getString("id"));
    System.out.println("name="+subI.getString("name"));
}               

以下是我的 json 作为 REST api 调用的响应。

{
  "menu": {
    "items": [{
            "id": 1,
            "code": "hot1_sub1_mnu",
            "name": "Mutton",
            "status": "1",
            "sub_items": [{
                "id": "01",
                "name": "Mutton Pepper Fry",
                "price": "100"
            }, {
                "id": "02",
                "name": "Mutton Curry",
                "price": "100"
            }]
        },
        {
            "id": "2",
            "code": "hot1_sub2_mnu",
            "name": "Sea Food",
            "status": "1",
            "sub_items": [{
                "id": "01",
                "name": "Fish Fry",
                "price": "150"
            }]
        },
        {
            "id": "3",
            "code": "hot1_sub3_mnu",
            "name": "Noodles",
            "status": "1",
            "sub_items": [{
                "id": "01",
                "name": "Chicken Noodles",
                "price": "70"
            }, {
                "id": "02",
                "name": "Egg Noodles",
                "price": "60"
            }]
        }
    ]
}}

【问题讨论】:

标签: java json parsing gson


【解决方案1】:

正如我所说,我的 JSON 是来自 REST api 调用的响应,它有 7300 行长,如下图所示,如代码美化器所示。

object      {3}
    infoTransferReqResp     {1}
paramExtens :   null
    pageGroups      {1}
    pageGroups      [1]
    0       {4}
page_group_name :   LFG - LG - Insured Summary
page_group_id   :   8100
    **pages     [3]**
    repeatingBlocks     {1}

我需要从“Pages”数组中提取字符串值“questionText”。我使用带有导航路径的 jsonPath() 方法解决了这个问题。

JsonPath                 jsonPathEvaluator = response.jsonPath();
List<List<List<String>>> questions         = jsonPathEvaluator.getList("pageGroups.pageGroups.pages.questions.questionText");

它给了我 3 个 ArrayLists 一个嵌入另一个对应于 3 个“pages”数组

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多