日期:2014-05-16  浏览次数:20391 次

jackson用类似xpath的方式读取、修改json

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);