标签:
相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。
一、准备工作
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
2、 测试类基本代码如下
1 package com.hoo.test; 2 3 import java.io.IOException; 4 import java.io.StringWriter; 5 import java.util.ArrayList; 6 import java.util.HashMap; 7 import java.util.Iterator; 8 import java.util.LinkedHashMap; 9 import java.util.List; 10 import java.util.Map; 11 import java.util.Set; 12 import org.codehaus.jackson.JsonEncoding; 13 import org.codehaus.jackson.JsonGenerationException; 14 import org.codehaus.jackson.JsonGenerator; 15 import org.codehaus.jackson.JsonParseException; 16 import org.codehaus.jackson.map.JsonMappingException; 17 import org.codehaus.jackson.map.ObjectMapper; 18 import org.codehaus.jackson.node.JsonNodeFactory; 19 import org.codehaus.jackson.xml.XmlMapper; 20 import org.junit.After; 21 import org.junit.Before; 22 import org.junit.Test; 23 import com.hoo.entity.AccountBean; 24 /** 25 * <b>function:</b>Jackson 将java对象转换成JSON字符串,也可以将JSON字符串转换成java对象 26 * jar-lib-version: jackson-all-1.6.2 27 * jettison-1.0.1 28 * @file JacksonTest.java 29 * @package com.hoo.test 30 * @project Spring3 31 * @blog http://blog.csdn.net/IBM_hoojo 32 * @email hoojo_@126.com 33 * @version 1.0 34 */ 35 @SuppressWarnings("unchecked") 36 public class JacksonTest { 37 private JsonGenerator jsonGenerator = null; 38 private ObjectMapper objectMapper = null; 39 private AccountBean bean = null; 40 41 @Before 42 public void init() { 43 bean = new AccountBean(); 44 bean.setAddress("china-Guangzhou"); 45 bean.setEmail("hoojo_@126.com"); 46 bean.setId(1); 47 bean.setName("hoojo"); 48 objectMapper = new ObjectMapper(); 49 try { 50 jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8); 51 } catch (IOException e) { 52 e.printStackTrace(); 53 } 54 } 55 56 @After 57 public void destory() { 58 try { 59 if (jsonGenerator != null) { 60 jsonGenerator.flush(); 61 } 62 if (!jsonGenerator.isClosed()) { 63 jsonGenerator.close(); 64 } 65 66 jsonGenerator = null; 67 objectMapper = null; 68 bean = null; 69 System.gc(); 70 } catch (IOException e) { 71 e.printStackTrace(); 72 } 73 } 74 }
3、 所需要的JavaEntity
1 package com.hoo.entity; 2 3 public class AccountBean { 4 private int id; 5 private String name; 6 private String email; 7 private String address; 8 private Birthday birthday; 9 //getter、setter 10 11 @Override 12 public String toString() { 13 return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email; 14 } 15 } 16 17 //Birthday类 18 package com.hoo.entity; 19 20 public class Birthday { 21 private String birthday; 22 public Birthday(String birthday) { 23 super(); 24 this.birthday = birthday; 25 } 26 //getter、setter 27 28 public Birthday() {} 29 30 @Override 31 public String toString() { 32 return this.birthday; 33 } 34 }
二、Java对象转换成JSON
1、 JavaBean(Entity/Model)转换成JSON
1 /** 2 * <b>function:</b>将java对象转换成json字符串 3 */ 4 @Test 5 public void writeEntityJSON() { 6 try { 7 System.out.println("jsonGenerator"); 8 //writeObject可以转换java对象,eg:JavaBean/Map/List/Array等 9 jsonGenerator.writeObject(bean); 10 System.out.println(); 11 System.out.println("ObjectMapper"); 12 //writeValue具有和writeObject相同的功能 13 objectMapper.writeValue(System.out, bean); 14 15 } catch (IOException e) { 16 e.printStackTrace(); 17 } 18 }
运行后结果如下:
1 jsonGenerator 2 {"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"} 3 4 ObjectMapper 5 {"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}
上面分别利用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、 将Map集合转换成Json字符串
1 /** 2 * <b>function:</b>将map转换成json字符串 3 */ 4 @Test 5 public void writeMapJSON() { 6 try { 7 Map<String, Object> map = new HashMap<String, Object>(); 8 map.put("name", bean.getName()); 9 map.put("account", bean); 10 bean = new AccountBean(); 11 bean.setAddress("china-Beijin"); 12 bean.setEmail("hoojo@qq.com"); 13 map.put("account2", bean); 14 System.out.println("jsonGenerator"); 15 jsonGenerator.writeObject(map); 16 System.out.println(""); 17 System.out.println("objectMapper"); 18 objectMapper.writeValue(System.out, map); 19 } catch (IOException e) { 20 e.printStackTrace(); 21 } 22 }
转换后结果如下:
1 jsonGenerator 2 {"account2":{"address":"china-Beijin","name":null,"id":0,"birthday":null,"email":"hoojo@qq.com"},"name":"hoojo", 3 "account":{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}} 4 5 objectMapper 6 {"account2":{"address":"china-Beijin","name":null,"id":0,"birthday":null,"email":"hoojo@qq.com"},"name":"hoojo", 7 "account":{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}}
3、 将List集合转换成json
1 /** 2 * <b>function:</b>将list集合转换成json字符串 3 */ 4 @Test 5 public void writeListJSON() { 6 try { 7 List<AccountBean> list = new ArrayList<AccountBean>(); 8 list.add(bean); 9 bean = new AccountBean(); 10 bean.setId(2); 11 bean.setAddress("address2"); 12 bean.setEmail("email2"); 13 bean.setName("haha2"); 14 list.add(bean); 15 System.out.println("jsonGenerator"); 16 //list转换成JSON字符串 17 jsonGenerator.writeObject(list); 18 System.out.println(); 19 System.out.println("ObjectMapper"); 20 //用objectMapper直接返回list转换成的JSON字符串 21 System.out.println("1###" + objectMapper.writeValueAsString(list)); 22 System.out.print("2###"); 23 //objectMapper list转换成JSON字符串 24 objectMapper.writeValue(System.out, list); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 }
结果如下:
1 jsonGenerator 2 [{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}, 3 {"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}] 4 5 ObjectMapper 6 1###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}, 7 {"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}] 8 2###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}, 9 {"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
外面就是多了个[]中括号;同样Array也可以转换,转换的JSON和上面的结果是一样的,这里就不再转换了。~.~
4、下面来看看jackson提供的一些类型,用这些类型完成json转换;如果你使用这些类型转换JSON的话,那么你即使没有 JavaBean(Entity)也可以完成复杂的Java类型的JSON转换。下面用到这些类型构建一个复杂的Java对象,并完成JSON转换。
1 @Test 2 public void writeOthersJSON() { 3 try { 4 String[] arr = { "a", "b", "c" }; 5 System.out.println("jsonGenerator"); 6 String str = "hello world jackson!"; 7 //byte 8 jsonGenerator.writeBinary(str.getBytes()); 9 //boolean 10 jsonGenerator.writeBoolean(true); 11 //null 12 jsonGenerator.writeNull(); 13 //float 14 jsonGenerator.writeNumber(2.2f); 15 //char 16 jsonGenerator.writeRaw("c"); 17 //String 18 jsonGenerator.writeRaw(str, 5, 10); 19 //String 20 jsonGenerator.writeRawValue(str, 5, 5); 21 //String 22 jsonGenerator.writeString(str); 23 jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str)); 24 System.out.println(); 25 26 //Object 27 jsonGenerator.writeStartObject();//{ 28 jsonGenerator.writeObjectFieldStart("user");//user:{ 29 jsonGenerator.writeStringField("name", "jackson");//name:jackson 30 jsonGenerator.writeBooleanField("sex", true);//sex:true 31 jsonGenerator.writeNumberField("age", 22);//age:22 32 jsonGenerator.writeEndObject();//} 33 jsonGenerator.writeArrayFieldStart("infos");//infos:[ 34 jsonGenerator.writeNumber(22);//22 35 jsonGenerator.writeString("this is array");//this is array 36 jsonGenerator.writeEndArray();//] 37 jsonGenerator.writeEndObject();//} 38 39 AccountBean bean = new AccountBean(); 40 bean.setAddress("address"); 41 bean.setEmail("email"); 42 bean.setId(1); 43 bean.setName("haha"); 44 45 //complex Object 46 jsonGenerator.writeStartObject();//{ 47 jsonGenerator.writeObjectField("user", bean);//user:{bean} 48 jsonGenerator.writeObjectField("infos", arr);//infos:[array] 49 jsonGenerator.writeEndObject();// 50 } 51 } catch (Exception e) { 52 e.printStackTrace(); 53 } 54 }
运行后,结果如下:
1 jsonGenerator 2 "aGVsbG8gd29ybGQgamFja3NvbiE=" true null 2.2c world jac worl "hello world jackson!" "hello world jackson!" 3 {"user":{"name":"jackson","sex":true,"age":22},"infos":[22,"this is array"]} 4 {"user":{"address":"address","name":"haha","id":1,"birthday":null,"email":"email"},"infos":["a","b","c"]}
怎么样?构造的json字符串和输出的结果是一致的吧。关键看懂用JSONGenerator提供的方法,完成一个Object的构建。
三、JSON转换成Java对象
1、 将json字符串转换成JavaBean对象
1 @Test 2 public void readJson2Entity() { 3 String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}"; 4 try { 5 AccountBean acc = objectMapper.readValue(json, AccountBean.class); 6 System.out.println(acc.getName()); 7 System.out.println(acc); 8 } catch (JsonParseException e) { 9 e.printStackTrace(); 10 } catch (JsonMappingException e) { 11 e.printStackTrace(); 12 } catch (IOException e) { 13 e.printStackTrace(); 14 } 15 }
很简单,用到了ObjectMapper这个对象的readValue这个方法,这个方法需要提供2个参数。第一个参数就是解析的JSON字符串,第二个 参数是即将将这个JSON解析吃什么Java对象,Java对象的类型。当然,还有其他相同签名方法,如果你有兴趣可以一一尝试使用方法,当然使用的方法 和当前使用的方法大同小异。运行后,结果如下:
1 haha 2 haha#1#address#null#email
2、 将json字符串转换成List<Map>集合
1 @Test 2 public void readJson2List() { 3 String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+ 4 "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]"; 5 try { 6 List<LinkedHashMap<String, Object>> list = objectMapper.readValue(json, List.class); 7 System.out.println(list.size()); 8 for (int i = 0; i < list.size(); i++) { 9 Map<String, Object> map = list.get(i); 10 Set<String> set = map.keySet(); 11 for (Iterator<String> it = set.iterator();it.hasNext();) { 12 String key = it.next(); 13 System.out.println(key + ":" + map.get(key)); 14 } 15 } 16 } catch (JsonParseException e) { 17 e.printStackTrace(); 18 } catch (JsonMappingException e) { 19 e.printStackTrace(); 20 } catch (IOException e) { 21 e.printStackTrace(); 22 } 23 }
尝试过将上面的JSON转换成List,然后List中存放AccountBean,但结果失败了。但是支持Map集合。因为你转成List.class,但是不知道List存放何种类型。只好默然Map类型。因为所有的对象都可以转换成Map结合,运行后结果如下:
1 2 2 address:address2 3 name:haha2 4 id:2 5 email:email2 6 address:address 7 name:haha 8 id:1 9 email:email
3、 Json字符串转换成Array数组,由于上面的泛型转换不能识别到集合中的对象类型。所有这里用对象数组,可以解决这个问题。只不过它不再是集合,而是一个数组。当然这个不重要,你可以用Arrays.asList将其转换成List即可。
1 @Test 2 public void readJson2Array() { 3 String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+ 4 "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]"; 5 try { 6 AccountBean[] arr = objectMapper.readValue(json, AccountBean[].class); 7 System.out.println(arr.length); 8 for (int i = 0; i < arr.length; i++) { 9 System.out.println(arr[i]); 10 } 11 } catch (JsonParseException e) { 12 e.printStackTrace(); 13 } catch (JsonMappingException e) { 14 e.printStackTrace(); 15 } catch (IOException e) { 16 e.printStackTrace(); 17 } 18 }
运行后的结果:
1 2 2 haha2#2#address2#null#email2 3 haha#1#address#null#email
4、 Json字符串转换成Map集合
1 @Test 2 public void readJson2Map() { 3 String json = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+ 4 "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}"; 5 try { 6 Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class); 7 System.out.println(maps.size()); 8 Set<String> key = maps.keySet(); 9 Iterator<String> iter = key.iterator(); 10 while (iter.hasNext()) { 11 String field = iter.next(); 12 System.out.println(field + ":" + maps.get(field)); 13 } 14 } catch (JsonParseException e) { 15 e.printStackTrace(); 16 } catch (JsonMappingException e) { 17 e.printStackTrace(); 18 } catch (IOException e) { 19 e.printStackTrace(); 20 } 21 }
运行后结果如下:
1 3 2 success:true 3 A:{address=address2, name=haha2, id=2, email=email2} 4 B:{address=address, name=haha, id=1, email=email}
四、Jackson对XML的支持
Jackson也可以完成java对象到xml的转换,转换后的结果要比json-lib更直观,不过它依赖于stax2-api.jar这个jar包。
1 /** 2 * <b>function:</b>java对象转换成xml文档 3 * 需要额外的jar包 stax2-api.jar 4 */ 5 @Test 6 public void writeObject2Xml() { 7 //stax2-api-3.0.2.jar 8 System.out.println("XmlMapper"); 9 XmlMapper xml = new XmlMapper(); 10 try { 11 //javaBean转换成xml 12 //xml.writeValue(System.out, bean); 13 StringWriter sw = new StringWriter(); 14 xml.writeValue(sw, bean); 15 System.out.println(sw.toString()); 16 //List转换成xml 17 List<AccountBean> list = new ArrayList<AccountBean>(); 18 list.add(bean); 19 list.add(bean); 20 System.out.println(xml.writeValueAsString(list)); 21 //Map转换xml文档 22 Map<String, AccountBean> map = new HashMap<String, AccountBean>(); 23 map.put("A", bean); 24 map.put("B", bean); 25 System.out.println(xml.writeValueAsString(map)); 26 } catch (JsonGenerationException e) { 27 e.printStackTrace(); 28 } catch (JsonMappingException e) { 29 e.printStackTrace(); 30 } catch (IOException e) { 31 e.printStackTrace(); 32 } 33 }
运行上面的方法,结果如下:
1 XmlMapper 2 3 <unknown><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></unknown> 4 <unknown><unknown><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></unknown> 5 <email><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></email></unknown> 6 <unknown><A><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></A> 7 <B><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></B></unknown>
看结果,根节点都是unknown 这个问题还没有解决,由于根节点没有转换出来,所有导致解析xml到Java对象,也无法完成。
标签:
原文地址:http://www.cnblogs.com/angleBlue/p/4801576.html