Java 获取JSONArray并写入JSONArray
我的目标如下:Java 获取JSONArray并写入JSONArray,java,json,java-8,Java,Json,Java 8,我的目标如下: { "some_prop": "sweetvalue", "some_list": ["0f9f822cd7e64000ac056ebc17b82f1d", "0f9f82223094fj7b82f1d"] } 我正在尝试获取一些列表并写入一些列表,然后保存到文件中。使用以下代码: public String getData(String key) { // this is confusion should be getConfigValue String da
{
"some_prop": "sweetvalue",
"some_list": ["0f9f822cd7e64000ac056ebc17b82f1d", "0f9f82223094fj7b82f1d"]
}
我正在尝试获取一些列表
并写入一些列表
,然后保存到文件中。使用以下代码:
public String getData(String key) { // this is confusion should be getConfigValue
String data = getConfig();
JSONObject jsonData;
Object content = null;
try {
jsonData = new JSONObject(data);
if (key != null) {
content = jsonData.getString(key);
} else {
content = jsonData.toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
return content.toString();
}
private void saveFile(String data) {
File file = configFile;
try (FileOutputStream fop = new FileOutputStream(file)) {
if (!file.exists()) file.createNewFile();
byte[] contentInBytes = data.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void appendToArrayValue(String uuid) {
JSONObject configData = new JSONObject(getConfig());
JSONArray mutedPlayers = configData.getJSONArray("some_list");
JSONArray uuidArray = new JSONArray(uuid);
JSONArray newArray = concatArray(mutedPlayers, uuidArray);
JSONObject newConfigData = configData.put("some_list", newArray);
saveFile(newConfigData.toString());
}
尝试运行此代码时,出现以下错误:
org.json.JSONException:JSONArray文本必须以“[”开头,位于1[字符2第1行]
我不确定到底出了什么问题,我知道我的代码很糟糕,但就是这样。看起来错误在第
JSONArray-uuidArray=new-JSONArray(uuid);
因为prevoius lineJSONArray mutedPlayers=configData.getJSONArray(“some_list”);
应该可以正常工作。
如果是这样的话,您就不会将数组传递给新的JSONArray(uuid)
,因为uuid是您的整个JSON对象