java - 在JAVA中的特定位置写入JSON文件

标签 java arrays json append

我需要一点帮助(如果这是一个愚蠢的问题,我很抱歉,但我是初学者,我多次尝试解决我的问题但没有成功......)

我想在 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/

相关文章:

尽管提供了 jar 文件,但未找到 java 类

java - 为什么Linux不执行Java有执行权限的bash脚本?

java - JAI 中的查找表

php - 将我的 php 脚本转换为 mysqli 时出现问题

c++ - 如何写一个不同大小的6维数组?

ruby-on-rails - Rails 5 允许 JSON 字段通过强参数不起作用

angularjs - 将 JSON 对象转换为 CSV 并将其保存到文件中

java - 如何在 java 中使用 .pem 文件证书发布数据

ios - 使用 init 将多个条目保存到结构 (swift4)

json - 使用 Dataweave 2.0 将 JSON 对象展开为嵌套的 JSON 对象