1

My original JSON saved on disk: R:\Desktop\alamo\dd

{
    "Name": "ABC.com",
    "Developer": "Ram Kumar",
    "Project List": [
        "Compnay: National",
        "Compnay: Enterprise",
        "Compnay: Alamo"
    ]
}

My code to remove a particular subNode: "Name"

public static void main(String[] args) throws IOException {
        String locationPath = "R:\\Desktop\\alamo\\dd";
        for (File locFile : new File(locationPath).listFiles()){
            ObjectMapper mapper = new ObjectMapper();
            ObjectNode obj = (ObjectNode) mapper.readTree(locFile);

            JsonNode tree1 = mapper.readTree(locFile); //Parse Specific JSON from Rental
            if(obj.has("Name")){
                obj.remove("Name");
                }
            System.out.println(obj);
            /* if(tree1.has("Name"))
            {
                ((ObjectNode) tree1).remove("Name");
            }*/
        }
    }

Output on console: {"Developer":"Ram Kumar","Project List":["Compnay: National","Compnay: Enterprise","Compnay: Alamo"]}

The output on console is correct as per modification but when i see my json file it still has Name subnode. How to write back?? Thanks

Joka Lee
  • 151
  • 1
  • 8
  • so you are asking how write a string to file? Convert node to string `mapper.writeValueAsString(node)` and write it to file – Adrian Apr 24 '19 at 08:19
  • Possible duplicate of [Is this the best way to rewrite the content of a file in Java?](https://stackoverflow.com/questions/1016278/is-this-the-best-way-to-rewrite-the-content-of-a-file-in-java) – Adrian Apr 24 '19 at 08:19
  • Consider the answer and let me know https://stackoverflow.com/questions/55824838/unable-to-save-modifies-json/55825505#55825505 – Googlian Apr 24 '19 at 08:27

1 Answers1

2

You have to just run FileWriter to write the removed string again into the file.

// If this output prints correct value then write value
System.out.println(obj);

FileWriter fw = new FileWriter(locationPath);
fw.write(obj.toString());
fw.close();
Googlian
  • 6,077
  • 3
  • 38
  • 44