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

时间:2015-04-10 03:38:12

标签: java json

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

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

我想删除

中的所有内容
  

"空":[

  

],

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

修改 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
}

现在我给出了一个错误:

  

线程中的异常" main" java.lang.ClassCastException:com.google.gson.JsonArray无法强制转换为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();
    }
}

4 个答案:

答案 0 :(得分:1)

使用像杰克逊这样的JSON库:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.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));
    }

}

输出:

{
  "key" : "value"
}

答案 1 :(得分:1)

使用以下代码从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
},

答案 2 :(得分:0)

如果你放了一个' ['在开头和']'在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
    }
]

所以最终的节目将是: -

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

答案 3 :(得分:0)

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

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.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包含:

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

输出是:

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