从JSON的文件中删除一个JSON数据

时间:2018-10-30 09:37:41

标签: java json jackson

我的JSON是:

{
  "errorMessages" : [ {
    "key" : "QUIESCE_FAILURE",
    "code" : "12345",
    "description" : "User already exists aaa",
    "reason" : "Username {user} is already added aaa",
    "resolution" : "Please provide a different username aaa",
    "more_information" : "more info aaa",
    "type" : "error aaa"
  }, {
    "key" : "DUPLICATE_USERS",
    "code" : "3114587",
    "description" : "Failed to quiesce database(s)",
    "reason" : "Database {database} on host {host} is not accessible",
    "resolution" : "Please check that the database is accessible",
    "more_information" : "kkkk",
    "type" : "error"
  } ]
}

我想使用杰克逊用代码3114587删除json。

我有什么建议吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

我想您将JSON内容作为File对象。 如果您将其作为URLInputStreamReaderString使用, 然后只需采用另一种readValue方法修改下面的代码即可。

使用软件包com.fasterxml.jackson.databind中的类 和com.fasterxml.jackson.databind.node 您可以直接实现目标。 读取JSON输入,查找并删除数组元素,然后写入JSON输出:

File file = ...;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);  // for pretty print
JsonNode jsonNode = objectMapper.readValue(file, JsonNode.class);
ArrayNode errorMessages = (ArrayNode) jsonNode.get("errorMessages");
for (int i = 0; i < errorMessages.size(); i++) {
    ObjectNode errorMessage = (ObjectNode) errorMessages.get(i);
    String code = errorMessage.get("code").asText();
    if (code.equals("3114587")) {
        errorMessages.remove(i);  // remove the element
    }
}
objectMapper.writeValue(System.out, jsonNode);

答案 1 :(得分:-1)

delete json[key];

将您的Json对象存储在变量名称json中。找到您要删除的密钥,它应该可以工作。