---
title: "jackson用类似xpath的方式读取、修改json"
author: "fandayrockworld"
date: "2012-09-13T14:42:22Z"
tags: []
categories: ["开源软件"]
slug: "jackson-xpath-json"
draft: false
lastmod: "2012-09-13T14:51:18Z"
id: 1677871
url: "https://fandayrockworld.iteye.com/blog/1677871"
---

jackson是一款效率极高的json处理工具，如果能用xpath读取xml的那种方式读取、修改json就更好了，翻看jackson的介绍文档后，发现真的有这样的方式，即jackson的Tree Model [http://wiki.fasterxml.com/JacksonInFiveMinutes#Tree\_Model\_Example](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);
```