目前我在文件 (name.json) 中有以下 json 数组对象。
[{
"name":"ray",
"value":"1"
},
]
现在我想在文件中的这个 Json 数组中使用 java.lang 添加一个元素。像这样:
[{
"name":"ray",
"value":"1"
},
{
"name":"john",
"value":"2"
}
]
一种方法是从文件中读取整个数组,将一个元素附加到该数组并将其写回 java 中的 json 文件。但这绝对不是完成这项任务的最佳方式。任何人都可以建议任何其他方式吗?
最佳答案
试试这个:
1 - 创建一个具有读/写权限(“rw”)的 RandomAccessFile 对象;
RandomAccessFile randomAccessFile = new RandomAccessFile("/path/to/file.json", "rw");
2 - 将文件光标设置到字符“]”的位置
long pos = randomAccessFile.length();
while (randomAccessFile.length() > 0) {
pos--;
randomAccessFile.seek(pos);
if (randomAccessFile.readByte() == ']') {
randomAccessFile.seek(pos);
break;
}
}
3 - 写一个逗号(如果不是第一个元素)、新的 json 元素和字符“]”
String jsonElement = "{ ... }";
randomAccessFile.writeBytes("," + jsonElement + "]");
4 - 关闭文件
randomAccessFile.close();
关于java - 使用 Java 将 JSON 元素附加到文件中的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26250009/