如何从java中的json文件中删除键和值

问题描述 投票:0回答:1

我有下一个 json 文件 我想删除 ProductCharacteristic ->name 的键和值。 在 Java 中如何实现?

`[

{ “id”:“0028167072_CO_FIX_INTTV_1008_P3909_IDX0”,

“状态”:“活动”,

“开始日期”:“2023-02-12T22:00:00Z”,

“地点”:[ {

“id”:“8”,

“公寓”:“578”,

“角色”:“QA”,

“@referredType”:“街道”

} ],

“产品特性”:[ {

“id”:“CH_100473”,

“valueId”:“CH12_1000374_VALUE04141”,

“值”:“LTS”,

“名称”:“计算机”

}

] }

java json parsing jsonnode
1个回答
0
投票

假设您有一个使用 Maven 设置的正确 Java 项目,并且您的

pom.xml
文件中有以下依赖项:

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

您可以按如下方式解析和编辑 JSON:

    public static void main(String[] args) {
        // Replace with your actual JSON string of load JSON from file
        String jsonString = "{ \"id\": \"0028167072_CO_FIX_INTTV_1008_P3909_IDX0\", \"status\": \"Active\", \"startDate\": \"2023-02-12T22:00:00Z\", \"place\": [ { \"id\": \"8\", \"apartment\": \"578\", \"role\": \"QA\", \"@referredType\": \"street\" } ], \"ProductCharacteristic\": [ { \"id\": \"CH_100473\", \"valueId\": \"CH12_1000374_VALUE04141\", \"value\": \"LTS\", \"name\": \"Computer\" } ] }";

        JSONObject jsonObject = new JSONObject(jsonString);
        JSONArray productCharacteristics = jsonObject.getJSONArray("ProductCharacteristic");

        // Iterate through each "ProductCharacteristic" object and remove the "name"
        // key-value pair
        for (int i = 0; i < productCharacteristics.length(); i++) {
            JSONObject productCharacteristic = productCharacteristics.getJSONObject(i);
            productCharacteristic.remove("name");
        }

        String updatedJsonString = jsonObject.toString();
        System.out.println("Modified JSON:\n" + updatedJsonString);
    }
© www.soinside.com 2019 - 2024. All rights reserved.