我有一个在线下载的 json 文件:
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
我想删除其中的所有内容
"empty": [
至
],
我花了几个小时研究正则表达式的东西,但我似乎不知道如何让它做我想做的事情。
编辑: 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
}
现在我遇到了一个错误:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.JsonArray cannot be cast to 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();
}
}
最佳答案
使用以下代码从 json 中删除元素 empty
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("File Path"));
jsonObject .remove("empty");
使用 jsonObject.toJSONString() 删除 empty
元素以获取目标 JSON 后,现在 JSON 的结构将如下所示
{
"price": 1,
"lowValue": 0,
"highValue": 0
},
关于java - 在 Java 中从 json 文件中删除 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29552921/