`
fandayrockworld
  • 浏览: 309197 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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);
0
4
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics