jackson是一款效率极高的json处理工具,如果能用xpath读取xml的那种方式读取、修改json就更好了,翻看jackson的介绍文档后,发现真的有这样的方式,即jackson的Tree Model http://wiki.fasterxml.com/JacksonInFiveMinutes#Tree_Model_Example
代码如下:
ObjectMapper m = new ObjectMapper();
// can either use mapper.readTree(JsonParser), or bind to JsonNode
JsonNode rootNode = m.readValue(new File("user.json"), JsonNode.class);
// ensure that "last name" isn't "Xmler"; if is, change to "Jsoner"
JsonNode nameNode = rootNode.path("name");
String lastName = nameNode.path("last").getTextValue().
if ("xmler".equalsIgnoreCase(lastName)) {
((ObjectNode)nameNode).put("last", "Jsoner");
}
// and write it out:
m.writeValue(new File("user-modified.json"), rootNode);
本文介绍如何使用Jackson的TreeModel API来高效地读取、修改JSON文件。通过示例代码展示了如何确保JSON中特定字段的值,并在必要时进行更改。
1614

被折叠的 条评论
为什么被折叠?



