如何在java中附加到json文件

时间:2017-12-04 14:02:06

标签: java json

我有这个js.json文件

我想在文件中添加另一个块。

现在的文件 - >

[
{
"diff":"Easy",
"qus":"John1"
}
]

我希望如何 - >

[
{
"diff":"Easy",
"qus":"John1"
},
{
"diff":"Avg",
"qus":"John2"
}
]

2 个答案:

答案 0 :(得分:0)

您可以使用org.json库,如下所示:

JSONArray jsonarray = new JSONArray(jsonStr); //from the file
JSONObject jsonobject = new JSONObject(yourNewlyJsonObject);
jsonarray.put(jsonobject);
System.out.println(jsonarray.toString()); // or write it back to the file

答案 1 :(得分:0)

您可以查看此代码。

JSONObject obj = new JSONObject({
    "diff":"Avg",
    "qus":"John2"
    }); 


JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));   // reading the file and creating a json array of it.

a.put(obj);   // adding your created object into the array


// writing the JSONObject into a file(info.json)
        try {
            FileWriter fileWriter = new FileWriter("c:\\exer4-courses.json");         // writing back to the file
            fileWriter.write(a.toJSONString());
            fileWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

参考文献:

https://www.javatpoint.com/json-tutorial

http://www.vogella.com/tutorials/JavaIO/article.html