2

I'm having trouble appending to a JSON file. I can add the new entry but not insert it into the correct position.

Code:

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

    {
        File file = new File("jsonFormatting.json");
        if (!file.exists()) {
            System.out.println("No file");
        } else {
            try {
                JSONParser parser = new JSONParser();
                Object obj = parser.parse(new FileReader("jsonFormatting.json"));
                JSONObject jsonObject = (JSONObject) obj;
                JSONArray jsonItemInfo = (JSONArray) jsonObject.get("itemInfo");

                JSONObject newObject = new JSONObject();

                newObject.put("item", new Integer(10003));
                newObject.put("name", "ID10003");

                StringWriter out = new StringWriter();
                newObject.writeJSONString(out);
                String jsonText = out.toString();
                System.out.println(jsonText);

                jsonItemInfo.add(newObject);

                FileWriter fileToWrite = new FileWriter("jsonFormatting.json", true);
                try {
                    fileToWrite.write(jsonItemInfo.toJSONString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                fileToWrite.flush();
                fileToWrite.close();

            } catch (IOException | ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

JSON file:

"sampleArray": [
    "Element_0",
    "Element_1"
],
"dataPoint_1": 40,
"dataPoint_2": 500,
"dataPoint_3": 650,
"itemInfo": [
    {
        "item": "10001",
        "name": "ID10001",
    },
    {
        "item": "10002",
        "name": "ID10002",
    }
]

I would like to add the following into the "itemInfo":

    {
        "item": "10003",
        "name": "ID10003",
    }

However, when I run my Java code, it adds this to the end of the JSON file, rather than inserting the new entry following the original 2:

[{"item":"10001","name":"ID10001"},{"item":"10002","name":"ID10002"},{"item":10003,"name":"ID10003"}]

Thanks in advance for any advice you may offer!

quid pro quo
  • 23
  • 1
  • 4
  • 1
    After further research, it would appear I can't insert the addition into a specific location in the file. I would have to load the file into memory, perform the changes then rebuild the entire JSON and overwrite the original. Can anyone confirm this? – quid pro quo Nov 30 '16 at 00:44
  • One question can you confirm that your json file data that is the same as you pasted in the question (Json File Section), than i can have a look into the issue? – Bill Nov 30 '16 at 00:48
  • It is indeed as in the file, however the wrapping brackets around the entirety of the code are missing { }. For whatever reason Stackoverflow's code insert would not accept it in the block. – quid pro quo Nov 30 '16 at 01:04
  • FileWriter fileToWrite = new FileWriter("jsonFormatting.json", false); try this change in the code – Bill Nov 30 '16 at 01:07

1 Answers1

1

I run this code and it is working fine can you test this stuff on your side. If i understand you question correct.

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

            {
                File file = new File("jsonFormatting.json");
                if (!file.exists()) {
                    System.out.println("No file");
                } else {
                    try {
                        JSONParser parser = new JSONParser();
                        Object obj = parser.parse(new FileReader("jsonFormatting.json"));
                        JSONObject jsonObject = (JSONObject) obj;
                        JSONArray jsonItemInfo = (JSONArray) jsonObject.get("itemInfo");

                        JSONObject newObject = new JSONObject();

                        newObject.put("item", new Integer(10003));
                        newObject.put("name", "ID10003");

                        StringWriter out = new StringWriter();
                        newObject.writeJSONString(out);
                        String jsonText = out.toString();
                        System.out.println(jsonText);

                        jsonItemInfo.add(newObject);
                        jsonObject.put("itemInfo", jsonItemInfo);
                        FileWriter fileToWrite = new FileWriter("jsonFormatting.json", false);
                        try {
                            fileToWrite.write(jsonObject.toJSONString());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        fileToWrite.flush();
                        fileToWrite.close();

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }

my jsonFormatting.json file data look like

{"sampleArray": [
    "Element_0",
    "Element_1"
],
"dataPoint_1": 40,
"dataPoint_2": 500,
"dataPoint_3": 650,
"itemInfo": [
    {
        "item": "10001",
        "name": "ID10001"
    },
    {
        "item": "10002",
        "name": "ID10002"
    }
]
}

and output is

{
    "sampleArray": [
        "Element_0",
        "Element_1"
    ],
    "itemInfo": [
        {
            "item": "10001",
            "name": "ID10001"
        },
        {
            "item": "10002",
            "name": "ID10002"
        },
        {
            "item": 10003,
            "name": "ID10003"
        }
    ],
    "dataPoint_2": 500,
    "dataPoint_1": 40,
    "dataPoint_3": 650
}
Bill
  • 91
  • 2