从 Java 中的 json 文件中删除 json 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29552921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:29:50  来源:igfitidea点击:

Removing a json object from a json file in Java

javajson

提问by Corey

I have this json file I downloaded online:

我有我在线下载的这个json文件:

 {
"price": 1,
"empty": [
  0,
  0,
  0,
  0,
  0
],
"lowValue": 0,
"highValue": 0
},

and I want to delete everything from

我想从中删除所有内容

"empty": [

“空的”: [

to

],

],

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.

我花了几个小时看正则表达式的东西,我似乎无法弄清楚如何让它做我想要它做的事情。

Edit:Annamalai Thangaraj's method works until I add more to the file.

编辑: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
}

which now I'm given an error:

现在我得到了一个错误:

Exception in thread "main" java.lang.ClassCastException: com.google.gson.JsonArray cannot be cast to com.google.gson.JsonObject

线程“main”中的异常 java.lang.ClassCastException: com.google.gson.JsonArray 无法转换为 com.google.gson.JsonObject

My code is exactly:

我的代码正是:

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();
    }
}

回答by Annamalai Thangaraj

Use the following code to remove element emptyfrom json

使用以下代码empty从 json 中删除元素

JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("File Path"));
jsonObject .remove("empty");

After removing emptyelement using jsonObject.toJSONString() to get target JSON, Now structure of JSON will be look like this

empty使用 jsonObject.toJSONString()删除元素以获取目标 JSON 后,现在 JSON 的结构将如下所示

 {
"price": 1,
"lowValue": 0,
"highValue": 0
},

回答by Upio

Use a JSON library like Hymanson:

使用像 Hymanson 这样的 JSON 库:

import com.fasterxml.Hymanson.databind.ObjectMapper;
import com.fasterxml.Hymanson.databind.node.ObjectNode;

import java.io.IOException;

public class JsonDelete {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        String json = "{\"key\":\"value\",\"empty\":[]}";

        ObjectNode node = (ObjectNode) mapper.readTree(json);
        node.remove("empty");

        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node));
    }

}

Outputs:

输出:

{
  "key" : "value"
}

回答by Kunal Talwadiya

If you put a '[' at the beginning and a ']' at the end of json file, it becomes a valid json file. Like in your json file, It should be.

如果你在 json 文件的开头放一个 '[' ,在结尾放一个 ']',它就成为一个有效的 json 文件。就像在你的 json 文件中一样,它应该是。

[
    {
    "price": 1,
    "empty": [
      0,
      0,
      0,
      0,
      0
    ],
    "lowValue": 0,
    "highValue": 0
    },
    {
    "price": 500,
    "empty": [
      5,
      0,
      3,
      6,
      9
    ],
    "lowValue": 4,
    "highValue": 2
    }
]

So the final program will be like:--

所以最终的程序将是这样的:--

public class ReadJSONFromFile {
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        try {
            Object obj = parser.parse(new FileReader("locationOfFIle"));
            JSONArray array = (JSONArray) obj;
            FileWriter file = new FileWriter("locationOfFIle");
            for (int index = 0; index < array.size(); ++index) {
                JSONObject jsonObject = (JSONObject) array.get(index);
                jsonObject.remove("empty");
                file.write(jsonObject.toJSONString());
                file.flush();
                if (index == array.size() - 1)
                    file.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

回答by dieter

You can also parse your json by ignoring some fields. Look at this example:

您还可以通过忽略某些字段来解析您的 json。看这个例子:

import com.fasterxml.Hymanson.annotation.JsonIgnoreProperties;
import com.fasterxml.Hymanson.core.JsonParseException;
import com.fasterxml.Hymanson.databind.JsonMappingException;
import com.fasterxml.Hymanson.databind.ObjectMapper;

@JsonIgnoreProperties(value = { "empty" })
public class Item {

    private long price;
    private long lowValue;
    private long highValue;

    public long getPrice() {
        return price;
    }

    public void setPrice(long price) {
        this.price = price;
    }

    public long getLowValue() {
        return lowValue;
    }

    public void setLowValue(long lowValue) {
        this.lowValue = lowValue;
    }

    public long getHighValue() {
        return highValue;
    }

    public void setHighValue(long highValue) {
        this.highValue = highValue;
    }

    @Override
    public String toString() {
        return "Item [price=" + price + ", lowValue=" + lowValue + ", highValue=" + highValue + "]";
    }

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

        String file = "c:\json";

        ObjectMapper mapper = new ObjectMapper();

        Item[] items = mapper.readValue(new File(file), Item[].class);
        for (Item item : items) {
            System.out.println(item);
        }

    }

}

c:\json contains:

c:\json 包含:

    [
    {
        "price": 1,
        "empty": [
          0,
          0,
          0,
          0,
          0
        ],
        "lowValue": 0,
        "highValue": 0
    },
    {
        "price": 2,
        "empty": [
          0,
          0,
          0,
          0,
          0
        ],
        "lowValue": 3,
        "highValue": 4
    }
]

Output is:

输出是:

Item [price=1, lowValue=0, highValue=0]
Item [price=2, lowValue=3, highValue=4]