【发布时间】:2021-01-06 21:13:36
【问题描述】:
我可以使用 ObjectMapper 读取/修改 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)
【问题讨论】:
-
您需要在
ObjectMapper上启用INDENT_OUTPUT 功能。看看What is the simplest way to configure the indentation spacing on a Jackson ObjectMapper?