Ausgabe
Ich versuche, diese JSON-Datei zu aktualisieren:
{
"name": "abc",
"age": "123",
"project-name": "Test",
"city": "pune",
"project-git": "Test",
"notification": {
"email-subject": "Test"
}
}
Ich versuche zu ändern project-name
und email-subject
zu einem anderen Wert.
Der zu ändernde Code email-subject
lautet wie folgt:
ObjectMapper objectMapper = new ObjectMapper();
File jsonFile = new File("abc.json");
JsonNode root = objectMapper.readTree(jsonFile);
JsonNode steps = root.get("notification");
for (final JsonNode item: steps) {
if (item.findPath("email-subject") != null) {
((ObjectNode) item).put("email-subject", "Test update");
}
}
String resultJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);
Und der zu aktualisierende Code project-name
lautet wie folgt:
ObjectMapper objectMapper = new ObjectMapper();
File jsonFile = new File("bac.json");
JsonNode root = objectMapper.readTree(jsonFile);
((ObjectNode) item).put("project-name", "update name")
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);
In beiden Fällen bekomme ich diese Ausnahme:
Error : Exception in thread "main" java.lang.ClassCastException: com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
Jede Hilfe wäre willkommen
Lösung
notification
ist ein Objektknoten. Sie können direkt auf seine Felder zugreifen.
JsonNode root = objectMapper.readTree(jsonFile);
JsonNode steps = root.get("notification");
((ObjectNode) root).put("project-name", "update name");
if (((ObjectNode) steps).has("email-subject")) {
((ObjectNode) steps).put("email-subject", "Test update");
}
Beantwortet von – Raymond Choi
Antwort geprüft von – Senaida (FixError Volunteer)