从Java中的json文件中删除json对象 [英] Removing a json object from a json file in Java
问题描述
我有我在线下载的json文件:
I have this json file I downloaded online:
{
"price": 1,
"empty": [
0,
0,
0,
0,
0
],
"lowValue": 0,
"highValue": 0
},
我想从
空":[
到
],
我花了几个小时来查看正则表达式的内容,但似乎无法弄清楚如何使它做我想做的事.
I've spent a few hours looking at regex stuff and I can't seem to figure out how to make it do what I want it to do.
修改: Annamalai Thangaraj的方法可以起作用,直到我向文件中添加更多内容为止.
Annamalai Thangaraj's method works until I add more to the file.
{
"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
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
Use the following code to remove element empty
from json
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("File Path"));
jsonObject .remove("empty");
使用jsonObject.toJSONString()删除empty
元素以获取目标JSON之后,现在JSON的结构将如下所示
After removing empty
element using jsonObject.toJSONString() to get target JSON, Now structure of JSON will be look like this
{
"price": 1,
"lowValue": 0,
"highValue": 0
},
这篇关于从Java中的json文件中删除json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!