jackson中的tree model例子

今天继续jackson的学习,在JACKSON中,可以用TREE MODEL树型结构,象以DOM
的方式那样去读取结点,方法为:
  ObjectMapper mapper = new ObjectMapper();


BufferedReader fileReader = new BufferedReader(
new FileReader("c:\\user.json"));
JsonNode rootNode = mapper.readTree(fileReader);
JsonNode nameNode = rootNode.path("name");
System.out.println(nameNode.getTextValue());

比如一个user.json如下:
  {
  "age" : 29,
  "messages" : [ "msg 1", "msg 2", "msg 3" ],
  "name" : "mkyong"
}
下面一个完整的的例子演示了读取和修改结点
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
 
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
 
public class JacksonTreeNodeExample {
	public static void main(String[] args) {
 
		ObjectMapper mapper = new ObjectMapper();
 
		try {
 
			BufferedReader fileReader = new BufferedReader(
				new FileReader("c:\\user.json"));
			JsonNode rootNode = mapper.readTree(fileReader);
 
			/*** read ***/
			JsonNode nameNode = rootNode.path("name");
			System.out.println(nameNode.getTextValue());
 
			JsonNode ageNode = rootNode.path("age");
			System.out.println(ageNode.getIntValue());
 
			JsonNode msgNode = rootNode.path("messages");
			Iterator<JsonNode> ite = msgNode.getElements();
 
			while (ite.hasNext()) {
				JsonNode temp = ite.next();
				System.out.println(temp.getTextValue());
 
			}
 
			/*** update ***/
			((ObjectNode)rootNode).put("nickname", "new nickname");
			((ObjectNode)rootNode).put("name", "updated name");
			((ObjectNode)rootNode).remove("age");
 
			mapper.writeValue(new File("c:\\user.json"), rootNode);
 
		} catch (JsonGenerationException e) {
 
			e.printStackTrace();
 
		} catch (JsonMappingException e) {
 
			e.printStackTrace();
 
		} catch (IOException e) {
 
			e.printStackTrace();
 
		}
 
	}



输出:
mkyong
29
msg 1
msg 2
msg 3

并且这里修改了节点内容,重新写了新的JSON,所以新的JSON文件为:
{
  "messages" : [ "msg 1", "msg 2", "msg 3" ],
  "name" : "updated name",
  "nickname" : "new nickname"
}

你可能感兴趣的:(java,json,Jackson)