java - 在 Java 中从 json 文件中删除 json 对象

标签 java json

我有一个在线下载的 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/

相关文章:

java - 是否可以向 JSF bean 添加自定义验证?

java - 在另一个类中使用 JSONArray?

javascript - For循环: TypeError: Cannot read property '0' of undefined

java - Android Studio登录系统数据库问题

java - Wildfly忽略WEB-INF/lib中的库

java - Android ExpandableListView 填充了两次

java - 使用 FirebaseUI 在 Android TextView 中绑定(bind)嵌套的 JSON

Map键级别的Java并发锁

javascript - 将所有状态值传递给子组件

json - 如何将 JSON 数据 append 到现有的 JSON 文件 node.js