'How to update Rest API request Body array

I am trying to automate one API using rest API JAVA. I have kept sample request json in one file and before passing that json I want to modify some values. New values are in Map. For example I want to modify 'company' value to 'Microsoft'(which is in hashmap newInputs). Problem is my code is adding new 'company' at the top of body instead of updating it. How do i update specific values in Items array.

json body in file

{
        "Items": [
            {
                
                "newValue": "Q3",
                "company": "Test",
                "oldValue": "Q2",
                "Date": "2022-03-27"
            }
        ]
    }

What i want to pass to API

{
    "Items": [
        {
            
            "newValue": "Q3",
            "company": "Microsoft",
            "oldValue": "Q2",
            "Date": "2022-03-27"
        }
    ]
}

What my code is passing

{
    "company": "Microsoft",
    "Items": [
        {
            
            "newValue": "Q3",
            "company": "Test",
            "oldValue": "Q2",
            "Date": "2022-03-27"
        }
    ]
}

My code

public static String createItem(Map<String, String> newInputs) {
        JSONArray jsonArray = null;
        JSONObject jsonObject;
        
        try {

            jsonArray = new JSONArray(new String(
                    Files.readAllBytes(Paths.get("src", "test", "resources", "Payloads", "testdata.json"))));
            
            jsonObject = new JSONObject(jsonArray.get(0).toString());
            
            
            for (String key : newInputs.keySet()) {

                jsonObject.put(key, newInputs.get(key));
                }

                jsonArray.put(0, jsonObject);
            
            }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source