Paupiette
Paupiette

Reputation: 47

How to remove an element from a JSON file in JAVA

I have a JSON file That I want to read, iterate through its elements and then delete a specific element(UserID) in all the objects.

here's my Json file :

[
  {
    "UserID": 1,
    "UserName": "rooter",
    "Password": "12345",
    "Country": "UK",
    "Email": "[email protected]"
  },
  {
    "UserID": 2,
    "UserName": "binu",
    "Password": "123",
    "Country": "uk",
    "Email": "[email protected]"
  },
  {
    "UserID": 3,
    "UserName": "cal",
    "Password": "123",
    "Country": "uk",
    "Email": "[email protected]"
  },
  {
    "UserID": 4,
    "UserName": "nera",
    "Password": "1234",
    "Country": "uk",
    "Email": "[email protected]"
  }
]

I also used org.json.simple Library to read the file, parse its elements and remove one of those elements, and here's the code I used :

 public static void main(String[] args) throws Exception {


           JSONParser jsonparser = new JSONParser();
           try( FileReader reader = new FileReader("test.json"))
           {
            Object obj = jsonparser.parse(reader);
            ObjectMapper mapper = new ObjectMapper();
            JSONArray List = (JSONArray) obj;
            JsonNode root = mapper.readTree(reader);
            for (JsonNode jsonNode : root) {
                if (jsonNode instanceof ObjectNode) {
                    ObjectNode o = (ObjectNode) jsonNode;
                    o.remove("UserID");
                }
            }
            System.out.println(List);                          
        }
           catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }                    
     }

The problem is that it deletes the element when I parse it but doesn't change in the file, however I want to remove it from the file and save it back, do you have any idea how to do that.

Upvotes: 0

Views: 2474

Answers (2)

Ashish Karn
Ashish Karn

Reputation: 1143

Please check below-mentioned code which will help you to solve your issue:

public static void main(String[] args) throws Exception {

    JSONParser jsonparser = new JSONParser();
    try( FileReader reader = new FileReader("test.json"))
    {
        Object obj = jsonparser.parse(reader);
        JSONArray list = (JSONArray) obj;
        list.forEach(node->{
            ((JSONObject) node).remove("UserID");
        });
        System.out.println(list);
        saveAsJsonFile(list.toJSONString(),"test.json");
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

private static void saveAsJsonFile(String seasonData, String fileName) {
    try (final FileOutputStream outputStreamSeason = new FileOutputStream(fileName)) {//fileName is absolute path of file (dir + filename)
        outputStreamSeason.write(seasonData.getBytes());
        System.out.println(fileName + " file save successfully.");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Upvotes: 1

dovid
dovid

Reputation: 1

If the JSONArray List contains your edited JSON you should be able to get a JSON String from it using .toJSONString() and then write it to your file with a file writer like so:

try {
        fw = new FileWriter("test.json");
        fw.write(list.toJSONString());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        fw.close();  
    }

Upvotes: 0

Related Questions