我需要一点帮助(如果这是一个愚蠢的问题,我很抱歉,但我是初学者,我多次尝试解决我的问题但没有成功......)
我想在 JSON 文件中的特定位置写入,例如,为 Sarah (id 2) 添加新分数
[
{"id":1,"name":"Josh","score":["100","150","50"]},
{"id":2,"name":"Sarah","score":["150","200","200"]},
{"id":3,"name":"Thomas","score":["10","100","150"]},
]
至
[
{"id":1,"name":"Josh","score":["100","150","50"]},
{"id":2,"name":"Sarah","score":["150","200","200","300"]},
{"id":3,"name":"Thomas","score":["10","100","150"]},
]
最佳答案
导入类:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
从 json 文件中读取所有 Json 对象:
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("sample.json"))
{
//Read JSON file
Object obj = jsonParser.parse(reader);
JSONArray list= (JSONArray) obj;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
现在通过迭代来修改列表:
int count = list.length(); // get totalCount of all jsonObjects
for(int i=0 ; i< count; i++){ // iterate through jsonArray
JSONObject jsonObject = list.getJSONObject(i); // get jsonObject @ i position
}
在json文件中再次写入:
try (FileWriter file = new FileWriter("sample.json")) {
file.write(list.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
关于java - 在JAVA中的特定位置写入JSON文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59337354/