Jackson转换JSON

原文:http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html#top

 

Jackson框架

Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。

相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。

建议:JSON的转换使用Jackson框架;xml的转换使用xStream框架。

1. 准备工作

1.1. 下载依赖库jar包

Jackson的jar all下载地址:http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.jar

然后在工程中导入这个jar包即可开始工作

官方示例:http://wiki.fasterxml.com/JacksonInFiveMinutes

因为下面的程序是用junit测试用例运行的,所以还得添加junit的jar包。版本是junit-4.2.8

如果你需要转换xml,那么还需要stax2-api.jar

1.2. 所需要的JavaEntity

Birthday:

public class Birthday {

	private String birthday;

	public Birthday() {
	}

	public Birthday(String birthday) {
		this.birthday = birthday;
	}

	// getter、setter

	@Override
	public String toString() {
		return this.birthday;
	}
}

AccountBean:

public class AccountBean {

	private int id;

	private String name;

	private String email;

	private String address;

	private Birthday birthday;

	// getter、setter

	@Override
	public String toString() {
		return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
	}

}

2. Java对象转换成JSON

2.1. JavaBean(Entity/Model)转换成JSON 

import java.io.IOException;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

public class WriteEntityJSON {
	public static void main(String[] args) {
		AccountBean bean = new AccountBean();
		bean.setAddress("china-Guangzhou");
		bean.setEmail("[email protected]");
		bean.setId(1);
		bean.setName("hoojo");
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
			System.out.println("jsonGenerator");
			// writeObject可以转换java对象,eg:JavaBean/Map/List/Array等
			jsonGenerator.writeObject(bean);
			System.out.println();

			// writeValue具有和writeObject相同的功能
			System.out.println("ObjectMapper");
			objectMapper.writeValue(System.out, bean);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

运行后结果如下:

jsonGenerator
{"email":"[email protected]","birthday":null,"address":"china-Guangzhou","name":"hoojo","id":1}
ObjectMapper
{"email":"[email protected]","birthday":null,"address":"china-Guangzhou","name":"hoojo","id":1}

上面分别利用JsonGenerator的writeObject方法和ObjectMapper的writeValue方法完成对Java对象的转换,二者传递的参数及构造的方式不同;JsonGenerator的创建依赖于ObjectMapper对象。也就是说如果你要使用 JsonGenerator来转换JSON,那么你必须创建一个ObjectMapper。但是你用ObjectMapper来转换JSON,则不需要 JSONGenerator。

objectMapper的writeValue方法可以将一个Java对象转换成JSON。这个方法的参数一,需要提供一个输出流,转换后可以通过这个流来输出转换后的内容。或是提供一个File,将转换后的内容写入到File中。当然,这个参数也可以接收一个JSONGenerator,然后通过JSONGenerator来输出转换后的信息。第二个参数是将要被转换的Java对象。如果用三个参数的方法,那么是一个Config。这个config可以提供一些转换时的规则,过指定的Java对象的某些属性进行过滤或转换等。

2.2. 将Map集合转换成Json字符串

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

public class WriteMapJSON {
	public static void main(String[] args) {
		AccountBean bean1 = new AccountBean();
		bean1.setAddress("china-Suzhou");
		bean1.setEmail("[email protected]");
		bean1.setId(1);
		bean1.setName("zhangsan");
		
		AccountBean bean2 = new AccountBean();
		bean2.setAddress("china-Shanghai");
		bean2.setEmail("[email protected]");
		bean2.setId(2);
		bean2.setName("lisi");
		
        Map map = new HashMap();
        map.put("name1", bean1.getName());
        map.put("account1", bean1);
        map.put("name2", bean2.getName());
        map.put("account2", bean2);
        
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
			System.out.println("jsonGenerator");
			jsonGenerator.writeObject(map);
			System.out.println();

			System.out.println("ObjectMapper");
			objectMapper.writeValue(System.out, map);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

转换后结果如下:

jsonGenerator
{"account2":{"email":"[email protected]","birthday":null,"address":"china-Shanghai","name":"lisi","id":2},"account1":{"email":"[email protected]","birthday":null,"address":"china-Suzhou","name":"zhangsan","id":1},"name1":"zhangsan","name2":"lisi"}
ObjectMapper
{"account2":{"email":"[email protected]","birthday":null,"address":"china-Shanghai","name":"lisi","id":2},"account1":{"email":"[email protected]","birthday":null,"address":"china-Suzhou","name":"zhangsan","id":1},"name1":"zhangsan","name2":"lisi"}

2.3. 将List集合转换成json

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

public class WriteListJSON {
	public static void main(String[] args) {
		AccountBean bean1 = new AccountBean();
		bean1.setAddress("china-Suzhou");
		bean1.setEmail("[email protected]");
		bean1.setId(1);
		bean1.setName("zhangsan");

		AccountBean bean2 = new AccountBean();
		bean2.setAddress("china-Shanghai");
		bean2.setEmail("[email protected]");
		bean2.setId(2);
		bean2.setName("lisi");

		List list = new ArrayList();
		list.add(bean1);
		list.add(bean2);

		try {
			ObjectMapper objectMapper = new ObjectMapper();
			JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
			System.out.println("jsonGenerator");
			jsonGenerator.writeObject(list);
			System.out.println();

			System.out.println("ObjectMapper");
			objectMapper.writeValue(System.out, list);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

转换后结果如下:

jsonGenerator
[{"email":"[email protected]","birthday":null,"address":"china-Suzhou","name":"zhangsan","id":1},{"email":"[email protected]","birthday":null,"address":"china-Shanghai","name":"lisi","id":2}]
ObjectMapper
[{"email":"[email protected]","birthday":null,"address":"china-Suzhou","name":"zhangsan","id":1},{"email":"[email protected]","birthday":null,"address":"china-Shanghai","name":"lisi","id":2}]

外面就是多了个[]中括号;同样Array也可以转换,转换的JSON和上面的结果是一样的,这里就不再转换了。

2.4. Jackson类型使用

下面来看看jackson提供的一些类型,用这些类型完成json转换;如果你使用这些类型转换JSON的话,那么你即使没有JavaBean(Entity)也可以完成复杂的Java类型的JSON转换。下面用到这些类型构建一个复杂的Java对象,并完成JSON转换。

import java.io.IOException;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.JsonNodeFactory;

public class WriteListJSON {
	public static void main(String[] args) {
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
			String[] arr = { "a", "b", "c" };
			System.out.println("jsonGenerator");
			String str = "hello world jackson!";
			// byte
			jsonGenerator.writeBinary(str.getBytes());
			// boolean
			jsonGenerator.writeBoolean(true);
			// null
			jsonGenerator.writeNull();
			// float
			jsonGenerator.writeNumber(2.2f);
			// char
			jsonGenerator.writeRaw("c");
			// String
			jsonGenerator.writeRaw(str, 5, 10);
			// String
			jsonGenerator.writeRawValue(str, 5, 5);
			// String
			jsonGenerator.writeString(str);
			jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str));
			System.out.println();
			// Object
			jsonGenerator.writeStartObject();// {
			jsonGenerator.writeObjectFieldStart("user");// user:{
			jsonGenerator.writeStringField("name", "jackson");// name:jackson
			jsonGenerator.writeBooleanField("sex", true);// sex:true
			jsonGenerator.writeNumberField("age", 22);// age:22
			jsonGenerator.writeEndObject();// }
			jsonGenerator.writeArrayFieldStart("infos");// infos:[
			jsonGenerator.writeNumber(22);// 22
			jsonGenerator.writeString("this is array");// this is array
			jsonGenerator.writeEndArray();// ]
			jsonGenerator.writeEndObject();// }
			AccountBean bean = new AccountBean();
			bean.setAddress("address");
			bean.setEmail("email");
			bean.setId(1);
			bean.setName("haha");
			// complex Object
			jsonGenerator.writeStartObject();// {
			jsonGenerator.writeObjectField("user", bean);// user:{bean}
			jsonGenerator.writeObjectField("infos", arr);// infos:[array]
			jsonGenerator.writeEndObject();// }
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

转换后结果如下:

jsonGenerator
"aGVsbG8gd29ybGQgamFja3NvbiE=" true null 2.2c world jac  worl "hello world jackson!" "hello world jackson!"
 {"user":{"name":"jackson","sex":true,"age":22},"infos":[22,"this is array"]} {"user":{"email":"email","birthday":null,"address":"address","name":"haha","id":1},"infos":["a","b","c"]

3. JSON转换成Java对象

3.1. 将json字符串转换成JavaBean对象 

import java.io.IOException;

import org.codehaus.jackson.map.ObjectMapper;

public class ReadJson2Entity {
	public static void main(String[] args) {
		String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			AccountBean acc = objectMapper.readValue(json, AccountBean.class);
			System.out.println(acc.getName());
			System.out.println(acc);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

很简单,用到了ObjectMapper这个对象的readValue这个方法,这个方法需要提供2个参数。第一个参数就是解析的JSON字符串,第二个参数是即将将这个JSON解析吃什么Java对象,Java对象的类型。当然,还有其他相同签名方法,如果你有兴趣可以一一尝试使用方法,当然使用的方法 和当前使用的方法大同小异。运行后,结果如下:

haha
haha#1#address#null#email

3.2. 将json字符串转换成List集合

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.codehaus.jackson.map.ObjectMapper;

public class ReadJson2List {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
				+ "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			List> list = objectMapper.readValue(json, List.class);
			System.out.println(list.size());
			for (int i = 0; i < list.size(); i++) {
				Map map = list.get(i);
				Set set = map.keySet();
				for (Iterator it = set.iterator(); it.hasNext();) {
					String key = it.next();
					System.out.println(key + ":" + map.get(key));
				}
				System.out.println();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

尝试过将上面的JSON转换成List,然后List中存放AccountBean,但结果失败了。但是支持Map集合。因为你转成List.class,但是不知道List存放何种类型。只好默认Map类型。因为所有的对象都可以转换成Map结合,运行后结果如下:

2
address:address2
name:haha2
id:2
email:email2

address:address
name:haha
id:1
email:email

3.3. Json字符串转换成Array数组

由于上面的泛型转换不能识别到集合中的对象类型。所有这里用对象数组,可以解决这个问题。只不过它不再是集合,而是一个数组。当然这个不重要,你可以用Arrays.asList将其转换成List即可。

import java.io.IOException;

import org.codehaus.jackson.map.ObjectMapper;

public class ReadJson2Array {
	public static void main(String[] args) {
		String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
				+ "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			AccountBean[] arr = objectMapper.readValue(json, AccountBean[].class);
			System.out.println(arr.length);
			for (int i = 0; i < arr.length; i++) {
				System.out.println(arr[i]);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

运行后的结果:

2
haha2#2#address2#null#email2
haha#1#address#null#email

3.4. Json字符串转换成Map集合

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.codehaus.jackson.map.ObjectMapper;

public class ReadJson2Map {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		String json = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"
				+ "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			Map> maps = objectMapper.readValue(json, Map.class);
			System.out.println(maps.size());
			Set key = maps.keySet();
			Iterator iter = key.iterator();
			while (iter.hasNext()) {
				String field = iter.next();
				System.out.println(field + ":" + maps.get(field));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

运行后的结果:

3
success:true
A:{address=address2, name=haha2, id=2, email=email2}
B:{address=address, name=haha, id=1, email=email}


Jackson也可以完成java对象到xml的转换,但不建议使用该Jar执行转换。这里就不做介绍了。

你可能感兴趣的:(Jackson)