How remove key and value from json file in java

61 views Asked by At

I have the next json file I want remove key and value for ProductCharacteristic ->name. How it can be done in Java?

[

{ "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"

}

] }

]

1

There are 1 answers

1
Laurent On

Assuming you have a proper java project set up with Maven, and the following dependency in your pom.xml file:

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

You can parse and edit your JSON as follow:

    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);
    }