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

问题描述 投票:0回答:1

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

例如,我想在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"]},
]
java arrays json append
1个回答
0
投票

导入类:

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();
    }
© www.soinside.com 2019 - 2024. All rights reserved.