从 Java 中的 json 对象(json 文件)中移除 JSON 节点

Remove JSON node from json object (a json file) in Java

我正在尝试从 JSON 文件中删除几个节点。但是当我尝试删除节点时出现 class 强制转换异常。 java.lang.ClassCastException: class com.fasterxml.jackson.databind.node.TextNode cannot be cast to class com.fasterxml.jackson.databind.node.ObjectNode (com.fasterxml.jackson.databind.node.TextNode and com.fasterxml.jackson.databind.node.ObjectNode are in unnamed module of loader 'app')

我尝试了其他有用的 Whosebug 链接,但对我不起作用。这是我写的代码。

public static void removeNodes(String filePath, String... nodeNames) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNodes = objectMapper.readTree(new File(filePath));
        for (JsonNode node : jsonNodes) {
            ((ObjectNode) node).remove(Arrays.asList(nodeNames));
        }
        objectMapper
                .writerWithDefaultPrettyPrinter()
                .writeValue(new File(filePath.split("\.")[0] + "_modified.json"), jsonNodes);
    }

这是我正在阅读的 json 文件。

{
  "boolean_key": "--- true\n",
  "empty_string_translation": "",
  "key_with_description": "Check it out! This key has a description! (At least in some formats)",
  "key_with_line-break": "This translations contains\na line-break.",
  "nested": {
    "deeply": {
      "key": "Wow, this key is nested even deeper."
    },
    "key": "This key is nested inside a namespace."
  },
  "null_translation": null,
  "pluralized_key": {
    "one": "Only one pluralization found.",
    "other": "Wow, you have %s pluralizations!",
    "zero": "You have no pluralization."
  },
  "Dog_key": {
    "nest": "Only one pluralization found.",
    "sample_collection": [
    "first item",
    "second item",
    "third item"
  ],
  "Pest": "Only two pluralization found."
  },
  "simple_key": "Just a simple key with a simple message.",
  "unverified_key": "This translation is not yet verified and waits for it. (In some formats we also export this status)"
}

来电者:

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

// import static org.junit.jupiter.api.Assertions.*;

@RunWith(SpringRunner.class)
@SpringBootTest
class JSONUtilTest {

    @Test
    void removeNodes() throws IOException {
        JSONUtil.removeNodes("D:\data\JSON_A.json", "pluralized_key", "Dog_key", "simple_key");
    }
}

你能帮我找出导致问题的原因吗?

如评论中所述,您需要先解析 JSON 然后对其进行操作。

  • 读取文件。
  • 使用JSONParserparse()方法解析并转换为JSONObject
  • 移除你想要的节点。

使用 ObjectMapperwriterWithDefaultPrettyPrinter() 方法,您可以获得正确的缩进并将其写入输出文件。

代码如下:

public static void removeNodes(String filePath, String... nodeNames) {
   try (FileReader fileReader = new FileReader(filePath)) {
       JSONParser jsonParser = new JSONParser();
       JSONObject jsonObject = (JSONObject) jsonParser.parse(fileReader);

       Stream<String> nodeStream = Stream.of(nodeNames);
       nodeStream.forEach(jsonObject::remove);

       ObjectMapper objectMapper = new ObjectMapper();
       String jsonObjectPrettified = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);

       FileWriter fileWriter = new FileWriter(filePath.split("\.")[0] + "_modified.json");
       fileWriter.write(jsonObjectPrettified);
       fileWriter.close();

   } catch (IOException | ParseException e) {
       e.printStackTrace();
   }
}