0

I'm new to handling json files. Assume all the file contains key1

  • file1.txt -> {"key1":"ab","key2":"cd","key3":"ef"}
  • file2.txt -> {"key1":"gh","key4":"ij","key5":"kl"}
  • file3.txt -> {"key1":"mn","key3":"op","key4":"qr", "key5":"st"}
  • and so on

Now I want to make "key1":"xyz" for all files and the other keys remains same value present in that file. I had tried the following code.

String filePath = "D:\\json"
File folder = new File(filePath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) 
{
    JSONObject js = new JSONObject();
    js.remove("key1");
    js.put("key1", xyz);
    try (FileWriter fw = new FileWriter(filePath+ "\\" + listOfFiles[i].getName())) { 
        fw.write(js.toString()); 
        }
    catch (Exception e) {
        e.printStackTrace(); 
        }
}
  • output expected for file1 : {"key1":"xyz","key2":"cd","key3":"ef"}
  • but I got only {"key1":"xyz"} rest of them are gone.
CMY
  • 789
  • 5
  • 14
  • All of your JSON objects that you create are *default* empty objects as you're constructing them, `new JSONObject()` without passing in any parameters to the constructor. Instead pass in the data held in each text file so that you initialize the JSON object with that text. This is well explained in most any introductory JSON tutorial, and you'll want to have a look at one before moving forward (it makes use of this tool **much** easier). – Hovercraft Full Of Eels Sep 29 '16 at 15:46
  • Thank you, it is working when I passing the file content to the `JSONObject()` – CMY Sep 29 '16 at 16:43

0 Answers0