【问题标题】:how to update json array in java with existing json array value using java. Value are not updating in external json file如何使用 java 使用现有的 json 数组值更新 java 中的 json 数组。外部 json 文件中的值未更新
【发布时间】:2021-09-03 02:56:33
【问题描述】:

JSON 文件: [
{
“姓名”:“约翰”, “城市”:“柏林”, “工作”:“老师” }, {
"名称":"标记", "城市":"奥斯陆", “工作”:“医生” } ]

JSONParser 解析器 = 新 JSONParser(); JSONArray a = (JSONArray) parser.parse(new FileReader("F:\file.json"));

    for (Object o : a) {
        JSONObject person = (JSONObject) o;

        String name = (String) person.get("name");
        
        if (name.equalsIgnoreCase("john")) {
            String name1 = (String) person.get("name");
            System.out.println("name1" + name1);

            String city1 = (String) person.get("city");
            System.out.println("city1" + city1);

            String job1 = (String) person.get("job");
            System.out.println("job1" + job1);  
            
            person.put("city", "BLR");
            String city2 = (String) person.get("city");
            System.out.println("city2" + city2);
        }
    }

Json 外部文件中的值没有更新

【问题讨论】:

  • 保存 json 文件以便更新,您只是更改了不在本地文件中的对象的值

标签: java json


【解决方案1】:

JSONObject 是 json 的代表,它不链接到原始文件。 要重写文件,您需要更改 person 中的值并将其写入文件。

person.put("city", "BLR");
String jsonString = person.toString();
// write jsonString to file

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2017-09-19
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多