Jackson学习三之使用Tree Model读取以及更新JSON

依然是使用ObjectMapper,可以以类似读取DOM的方式读取JSON,请看例子:

package com.jingshou.jackson;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import org.apache.commons.io.IOUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTest4 {

	public static void main(String[] args) throws MalformedURLException, IOException {
		String url = "http://m.weather.com.cn/data/101210101.html";
		String json = IOUtils.toString(new URL(url));
		System.out.println(json);
		
		// Get rootNode and weather node;
		ObjectMapper m = new ObjectMapper();
		JsonNode rootNode = m.readTree(json);
		JsonNode weaNode = rootNode.get("weatherinfo");
		System.out.println(weaNode);
		System.out.println(weaNode.get("city"));
		
		System.out.println("***************************************");
		
		// Use Iterator to traverse to tree
		Iterator<String> keys = weaNode.fieldNames();	
		while(keys.hasNext()){
			String fieldName = keys.next();
			System.out.println(fieldName + ": " + weaNode.get(fieldName).textValue());
		}	

	}

}

 运行结果:

{"weatherinfo":{"city":"杭州","city_en":"hangzhou","date_y":"2014年1月12日","date":"","week":"星期日","fchh":"11","cityid":"101210101"......}
"杭州"
***************************************
city: 杭州
city_en: hangzhou
date_y: 2014年1月12日
date: 
week: 星期日
fchh: 11
cityid: 101210101
temp1: 5℃~0℃
temp2: 5℃~0℃
temp3: 6℃~-2℃
........

 

以下是新建以及更新Tree Model的例子:

package com.jingshou.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class JacksonTest5 {

	public static void main(String[] args) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		JsonNode rootNode = mapper.createObjectNode(); // will be of type ObjectNode
		((ObjectNode) rootNode).put("name", "jingshou");
		((ObjectNode) rootNode).put("id", 523);
		((ObjectNode) rootNode).put("age", 30);	
		System.out.println(rootNode);
		
		String json = mapper.writeValueAsString(rootNode);
		System.out.println(json);
		((ObjectNode) rootNode).remove("id");
		System.out.println(rootNode);

	}

}

 运行结果:

{"name":"jingshou","id":523,"age":30}
{"name":"jingshou","id":523,"age":30}
{"name":"jingshou","age":30}

 

参考文章:

本文出自"lijingshou"博客,转载请务必保留此出处http://lijingshou.iteye.com/blog/2003112

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