我有一个在线下载的 json 文件:
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
我想删除其中的所有内容
“空的”: [
to
],
我花了几个小时研究正则表达式的东西,但我似乎不知道如何让它做我想做的事情。
Edit:Annamalai Thangaraj 的方法在我向文件中添加更多内容之前一直有效。
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
{
"price": 500,
"empty": [
5,
0,
3,
6,
9
],
"lowValue": 4,
"highValue": 2
}
现在我收到一个错误:
线程“main”中的异常 java.lang.ClassCastException:com.google.gson.JsonArray 无法转换为 com.google.gson.JsonObject
我的代码正是:
public static void go() throws IOException {
JsonObject jsonObject = (JsonObject)JsonParser.parse(new FileReader(location));
jsonObject.remove("empty");
JsonArray jsonArray = (JsonArray)JsonParser.parse(new FileReader(location));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonObject.toString());
String prettyJsonString = gson.toJson(je);
FileWriter file = new FileWriter(System.getProperties().getProperty("user.home")+"\\output.json");
try {
file.write(prettyJsonString);
System.out.println("Successfully wrote JSON object to file.");
} catch (IOException e) {
e.printStackTrace();
} finally {
file.flush();
file.close();
}
}