【问题标题】:Write in JSON File in a specific position in JAVA在JAVA中的特定位置写入JSON文件
【发布时间】:2020-04-07 18:41:53
【问题描述】:

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

例如,我想在 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"]},
]

【问题讨论】:

  • 您可以使用诸如 GSON 或 Jackson 之类的库将您的 JSON 转换为 java 对象,之后您可以轻松操作 java 对象并使用 GSON/Jackson/whatever 将其转换回 JSON跨度>
  • (1) 将文件内容解析为 JSON 结构(此处为对象数组),(2) 修改所选对象,(3) 将 JSON 结构写回文件(替换其全部内容)。
  • 谢谢,所以我尝试解析字符串,但是当我替换我的 json 文件中的内容而不是“\”时,我不知道为什么
  • 在 JS 中,json[1].score.push(300)

标签: java arrays json append


【解决方案1】:

导入类:

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();
    }

【讨论】:

  • 我有一些错误:例如“找不到符号 JSONParser”,我正在用“javac -cp”json-simple-1.1.1.jar“test.java”编译,我没有知道我为什么收到这条消息
猜你喜欢
  • 2013-12-06
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
  • 2017-11-09
  • 2011-08-12
相关资源
最近更新 更多