【问题标题】:How to modify jackson jsonnode and write pretty json back in scala如何修改jackson jsonnode并在scala中写回漂亮的json
【发布时间】: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)

【问题讨论】:

标签: json scala jackson


【解决方案1】:

除了使用 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)

干杯!

【讨论】:

    猜你喜欢
    • 2023-02-22
    • 1970-01-01
    • 2021-07-05
    • 2015-09-08
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    相关资源
    最近更新 更多