Removing a json object from a json file in Java

后端 未结 4 1073
孤街浪徒
孤街浪徒 2021-01-22 13:25

I have this json file I downloaded online:

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

and I

4条回答
  •  清歌不尽
    2021-01-22 14:07

    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.

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

提交回复
热议问题