首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JSON文件中的remove方法而不是JSON数组删除JSON对象

使用JSON文件中的remove方法而不是JSON数组删除JSON对象
EN

Stack Overflow用户
提问于 2022-07-02 04:42:37
回答 1查看 134关注 0票数 1

我试图使用org.json库从JSON文件中删除JSON数组

我正试图从JSON文件中删除webAutomation JSON数组,如下所示

代码语言:javascript
复制
{
    "instructor": "Test_Instructor",
    "url": "www.google.com",
    "services": "Test Automation Service",
    "expertise": "Testing",
    "linkedIn": "linkedIn",
    "courses": {
        "webAutomation": [
            {
                "price": "500",
                "courseTitle": "Selenium"
            },
            {
                "price": "333",
                "courseTitle": "Protractor"
            }
        ],
        "apiAutomation": [
            {
                "price": "344.00",
                "courseTitle": "Rest Assured API Automation"
            }
        ],
        "mobileAutomation": [
            {
                "price": "4555",
                "courseTitle": "Appium"
            }
        ]
    }
}

我试着遵循密码。这里str有JSON文件

代码语言:javascript
复制
JSONObject jsonObject = new JSONObject(str);
jsonObject.getJSONObject("courses").getJSONArray("webAutomation");
System.out.println("after removal");
String str2 = mapper.writeValueAsString(jsonObject);
System.out.println(str2);

这将删除整个JSON对象,而不仅仅是JSON。输出为{"empty":false} --请帮助

EN

回答 1

Stack Overflow用户

发布于 2022-07-02 08:30:57

您可以在remove中使用org.json.JSONObject#remove方法。

代码语言:javascript
复制
JSONObject json = new JSONObject(str);
json.getJSONObject("courses").remove("webAutomation");
System.out.println(json);

产出如下:

代码语言:javascript
复制
{
    "instructor": "Test_Instructor",
    "url": "www.google.com",
    "services": "Test Automation Service",
    "expertise": "Testing",
    "linkedIn": "linkedIn",
    "courses": {
        "apiAutomation": [
            {
                "price": "344.00",
                "courseTitle": "Rest Assured API Automation"
            }
        ],
        "mobileAutomation": [
            {
                "price": "4555",
                "courseTitle": "Appium"
            }
        ]
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72836494

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档