参考:http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html
在其基础上做了稍微调整
详情见附件
jackson API文档:http://tool.oschina.net/apidocs/apidoc?api=jackson-1.9.9
Jackson 框架,轻易转换JSON
Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。
一、准备工作
pom.xml 里关联jar包如下:
4.0.0 com.waegg jacksonTest 0.0.1-SNAPSHOT junit junit 4.12 org.codehaus.jackson jackson-mapper-asl 1.9.13 com.fasterxml.jackson.dataformat jackson-dataformat-xml 2.7.1 war
二、Bean代码
AccountBean :
package com.bugyun.pojo;
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;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Birthday getBirthday() {
return birthday;
}
public void setBirthday(Birthday birthday) {
this.birthday = birthday;
}
}
Birthday:
package com.bugyun.pojo;
public class Birthday {
private String birthday;
public Birthday(String birthday) {
super();
this.birthday = birthday;
}
// getter、setter
public Birthday() {
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return this.birthday;
}
}
三、测试代码
package com.bugyun.test;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.bugyun.pojo.AccountBean;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
/**
* 项目名称:jacksonTest
* 类名称:JacksonTest.java
* 类描述:
* 创建人:beyond
* 创建时间:2016年2月24日 上午11:24:33
* 修改人:
* 修改时间:
* 修改备注:
* @version
*/
public class JacksonTest {
private JsonGenerator jsonGenerator = null;
private ObjectMapper objectMapper = null;
private AccountBean bean = null;
@Before
public void init() {
bean = new AccountBean();
bean.setAddress("js_wuxi");
bean.setEmail("[email protected]");
bean.setId(1);
bean.setName("bugyun");
objectMapper = new ObjectMapper();
try {
jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
} catch (IOException e) {
e.printStackTrace();
}
}
@After
public void destory() {
try {
if (jsonGenerator != null) {
jsonGenerator.flush();
}
if (!jsonGenerator.isClosed()) {
jsonGenerator.close();
}
jsonGenerator = null;
objectMapper = null;
bean = null;
System.gc();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @description: JavaBean(Entity/Model)转换成JSON
* 上面分别利用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对象的某些属性进行过滤或转换等。
*
* 输出:
* jsonGenerator {"id":1,"name":"bugyun","email":"[email protected]","address":"js_wuxi","birthday":null}
* ObjectMapper {"id":1,"name":"bugyun","email":"[email protected]","address":"js_wuxi","birthday":null}
* @return void
* @throws
* @author beyond
* @data:2016年2月24日上午11:34:53
*/
@Test
public void writeEntityJSON() {
try {
System.out.println("jsonGenerator");
jsonGenerator.writeObject(bean);
System.out.println("\nObjectMapper");
objectMapper.writeValue(System.out, bean);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @description: 将Map集合转换成Json字符串
* 输出:
* jsonGenerator {"name":"bugyun","account":{"id":1,"name":"bugyun","email":"[email protected]","address":"js_wuxi","birthday":null}}
* ObjectMapper {"name":"bugyun","account":{"id":1,"name":"bugyun","email":"[email protected]","address":"js_wuxi","birthday":null}}
* @return void
* @throws
* @author beyond
* @data:2016年2月24日上午11:41:48
*/
@Test
public void writeMapJSON() {
try {
Map map = new HashMap();
map.put("name", bean.getName());
map.put("account", bean);
System.out.println("jsonGenerator");
jsonGenerator.writeObject(map);
System.out.println("\n ObjectMapper");
objectMapper.writeValue(System.out, map);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @description: 将List集合转换成json
* 外面就是多了个[]中括号;同样Array也可以转换,转换的JSON和上面的结果是一样的
* 输出:
* jsonGenerator [{"id":1,"name":"bugyun","email":"[email protected]","address":"js_wuxi","birthday":null}]
* ObjectMapper 1###[{"id":1,"name":"bugyun","email":"[email protected]","address":"js_wuxi","birthday":null}]
* 2###[{"id":1,"name":"bugyun","email":"[email protected]","address":"js_wuxi","birthday":null}]
* @return void
* @throws
* @author beyond
* @data:2016年2月24日上午11:46:41
*/
@Test
public void writeListJSON() {
try {
List list = new ArrayList();
list.add(bean);
System.out.println("jsonGenerator");
jsonGenerator.writeObject(list);
System.out.println("\nObjectMapper");
System.out.println("1###" + objectMapper.writeValueAsString(list));
System.out.print("2###");
objectMapper.writeValue(System.out, list);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @description: 复杂的Java类型的JSON转换
* 输出:
* {"user":{"name":"jackson","sex":true,"age":22},"infos":[22,"this is array"]}
* {"user":{"id":1,"name":"haha","email":"email","address":"address","birthday":null},"infos":["a","b","c"]}
* @return void
* @throws
* @author beyond
* @data:2016年2月24日下午1:08:06
*/
@Test
public void writeOthersJSON() {
try {
String[] arr = { "a", "b", "c" };
//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");
jsonGenerator.writeStartObject();//{
jsonGenerator.writeObjectField("user", bean);//user:{bean}
jsonGenerator.writeObjectField("infos", arr);//infos:[array]
jsonGenerator.writeEndObject();//}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @description: 将json字符串转换成JavaBean对象
* 用到了ObjectMapper这个对象的readValue这个方法,这个方法需要提供2个参数。
* 第一个参数就是解析的JSON字符串,
* 第二个参数是将这个JSON解析持什么Java对象,Java对象的类型。当然,还有其他相同签名方法。
*
* 输出:
* haha
* haha#1#address#null#email
* @return void
* @throws
* @author beyond
* @data:2016年2月24日下午3:37:50
*/
@Test
public void readJson2Entity() {
String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
try {
AccountBean acc = objectMapper.readValue(json, AccountBean.class);
System.out.println(acc.getName());
System.out.println(acc);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @description: json字符串转换成list