如何修改 jackson jsonnode 并在 scala 中写回 pretty json

How to modify jackson jsonnode and write pretty json back in scala

我可以使用 ObjectMapper read/modify json 节点。但是我没有找到将 pretty json 写回文件的方法。

val reader = new FileReader("env_config.json")
val mapper = new ObjectMapper()

// need to cast to ObjectNode because JsonNode is immutable
val objectNode = mapper.readTree(reader).asInstanceOf[ObjectNode]

// modify a field
objectNode("service_port", 1234)

// write back but not pretty
mapper.writeValue(Paths.get("env_config.json").toFile, objectNode)

// not working either
mapper.writeValue(Paths.get("env_config.json").toFile, objectNode.toPrettyString)

除了使用 Michal 建议的 INDENT_OUTPUT 功能外,我还找到了一个简单的方法来打印漂亮的照片:

val reader = new FileReader("env_config.json")
val mapper = new ObjectMapper()

// need to cast to ObjectNode because JsonNode is immutable
val objectNode = mapper.readTree(reader).asInstanceOf[ObjectNode]

// modify a field
objectNode("service_port", 1234)

// pass a DefaultPrettyPrinter instance to do the pretty print!
val writer = mapper.writer(new DefaultPrettyPrinter());
writer.writeValue(Paths.get("env_config.json").toFile, objectNode)

干杯!