码迷,mamicode.com
首页 > Web开发 > 详细

Jackson 框架JSON、XML、List、Map直接相互转换

时间:2018-04-27 23:58:14      阅读:372      评论:0      收藏:0      [点我收藏+]

标签:res   忘记   use   输出流   cti   xmlns   java   archive   trace   

博客分类:

 

参考: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可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。

 

一、准备工作

 pom.xml 里关联jar包如下:

 

Xml代码  技术分享图片
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.     <groupId>com.waegg</groupId>  
  5.     <artifactId>jacksonTest</artifactId>  
  6.     <version>0.0.1-SNAPSHOT</version>  
  7.   
  8.     <dependencies>  
  9.         <dependency>  
  10.             <groupId>junit</groupId>  
  11.             <artifactId>junit</artifactId>  
  12.             <version>4.12</version>  
  13.         </dependency>  
  14.         <dependency>  
  15.             <groupId>org.codehaus.jackson</groupId>  
  16.             <artifactId>jackson-mapper-asl</artifactId>  
  17.             <version>1.9.13</version>  
  18.         </dependency>  
  19.         <dependency>  
  20.             <groupId>com.fasterxml.jackson.dataformat</groupId>  
  21.             <artifactId>jackson-dataformat-xml</artifactId>  
  22.             <version>2.7.1</version>  
  23.         </dependency>  
  24.     </dependencies>  
  25.   
  26.     <packaging>war</packaging>  
  27. </project>  
 

 

二、Bean代码

   AccountBean :

 

Java代码  技术分享图片
  1. package com.bugyun.pojo;  
  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.   
  10.     // getter、setter  
  11.   
  12.     @Override  
  13.     public String toString() {  
  14.         return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;  
  15.     }  
  16.   
  17.     public int getId() {  
  18.         return id;  
  19.     }  
  20.   
  21.     public void setId(int id) {  
  22.         this.id = id;  
  23.     }  
  24.   
  25.     public String getName() {  
  26.         return name;  
  27.     }  
  28.   
  29.     public void setName(String name) {  
  30.         this.name = name;  
  31.     }  
  32.   
  33.     public String getEmail() {  
  34.         return email;  
  35.     }  
  36.   
  37.     public void setEmail(String email) {  
  38.         this.email = email;  
  39.     }  
  40.   
  41.     public String getAddress() {  
  42.         return address;  
  43.     }  
  44.   
  45.     public void setAddress(String address) {  
  46.         this.address = address;  
  47.     }  
  48.   
  49.     public Birthday getBirthday() {  
  50.         return birthday;  
  51.     }  
  52.   
  53.     public void setBirthday(Birthday birthday) {  
  54.         this.birthday = birthday;  
  55.     }  
  56. }  
 
Birthday:
Java代码  技术分享图片
  1. package com.bugyun.pojo;  
  2.   
  3. public class Birthday {  
  4.     private String birthday;  
  5.   
  6.     public Birthday(String birthday) {  
  7.         super();  
  8.         this.birthday = birthday;  
  9.     }  
  10.   
  11.     // getter、setter  
  12.   
  13.     public Birthday() {  
  14.     }  
  15.   
  16.     public String getBirthday() {  
  17.         return birthday;  
  18.     }  
  19.   
  20.     public void setBirthday(String birthday) {  
  21.         this.birthday = birthday;  
  22.     }  
  23.   
  24.     @Override  
  25.     public String toString() {  
  26.         return this.birthday;  
  27.     }  
  28. }  
 

 

 

三、测试代码

 

Java代码  技术分享图片
  1. package com.bugyun.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.List;  
  9. import java.util.Map;  
  10. import java.util.Set;  
  11.   
  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.junit.After;  
  19. import org.junit.Before;  
  20. import org.junit.Test;  
  21.   
  22. import com.bugyun.pojo.AccountBean;  
  23. import com.fasterxml.jackson.dataformat.xml.XmlMapper;  
  24.   
  25. /** 
  26.  * 项目名称:jacksonTest   
  27.  * 类名称:JacksonTest.java   
  28.  * 类描述:   
  29.  * 创建人:beyond   
  30.  * 创建时间:2016年2月24日 上午11:24:33   
  31.  * 修改人:   
  32.  * 修改时间:   
  33.  * 修改备注:   
  34.  * @version 
  35.  */  
  36. public class JacksonTest {  
  37.       
  38.     private JsonGenerator jsonGenerator = null;  
  39.     private ObjectMapper objectMapper = null;  
  40.     private AccountBean bean = null;  
  41.           
  42.     @Before  
  43.     public void init() {  
  44.         bean = new AccountBean();  
  45.         bean.setAddress("js_wuxi");  
  46.         bean.setEmail("bugyun@hotmail.com");  
  47.         bean.setId(1);  
  48.         bean.setName("bugyun");  
  49.   
  50.         objectMapper = new ObjectMapper();  
  51.         try {  
  52.             jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);  
  53.         } catch (IOException e) {  
  54.             e.printStackTrace();  
  55.         }  
  56.     }  
  57.       
  58.     @After  
  59.     public void destory() {  
  60.         try {  
  61.             if (jsonGenerator != null) {  
  62.                 jsonGenerator.flush();  
  63.             }  
  64.             if (!jsonGenerator.isClosed()) {  
  65.                 jsonGenerator.close();  
  66.             }  
  67.             jsonGenerator = null;  
  68.             objectMapper = null;  
  69.             bean = null;  
  70.             System.gc();  
  71.         } catch (IOException e) {  
  72.             e.printStackTrace();  
  73.         }  
  74.     }  
  75.       
  76.       
  77.     /** 
  78.      *  
  79.      * @description: JavaBean(Entity/Model)转换成JSON   
  80.      *      上面分别利用JsonGenerator的writeObject方法和ObjectMapper的writeValue方法完成对Java对象的转换,二者传递的参数及构造的方式不同; 
  81.      *      JsonGenerator的创建依赖于ObjectMapper对象。 
  82.      *      也就是说如果你要使用JsonGenerator来转换JSON,那么你必须创建一个ObjectMapper。 
  83.      *      但是你用ObjectMapper来转换JSON,则不需要JSONGenerator。objectMapper的writeValue方法可以将一个Java对象转换成JSON。 
  84.      *      这个方法的参数一,需要提供一个输出流,转换后可以通过这个流来输出转换后的内容。 
  85.      *      或是提供一个File,将转换后的内容写入到File中。当然,这个参数也可以接收一个JSONGenerator,然后通过JSONGenerator来输出转换后的信息。 
  86.      *      第二个参数是将要被转换的Java对象。如果用三个参数的方法,那么是一个Config。 
  87.      *      这个config可以提供一些转换时的规则,过指定的Java对象的某些属性进行过滤或转换等。   
  88.      *  
  89.      *      输出: 
  90.      *          jsonGenerator   {"id":1,"name":"bugyun","email":"bugyun@hotmail.com","address":"js_wuxi","birthday":null} 
  91.      *          ObjectMapper    {"id":1,"name":"bugyun","email":"bugyun@hotmail.com","address":"js_wuxi","birthday":null}  
  92.      * @return void    
  93.      * @throws 
  94.      * @author beyond 
  95.      * @data:2016年2月24日上午11:34:53 
  96.      */  
  97.     @Test  
  98.     public void writeEntityJSON() {  
  99.         try {  
  100.             System.out.println("jsonGenerator");  
  101.             jsonGenerator.writeObject(bean);      
  102.               
  103.             System.out.println("\nObjectMapper");  
  104.             objectMapper.writeValue(System.out, bean);  
  105.         } catch (IOException e) {  
  106.             e.printStackTrace();  
  107.         }  
  108.     }  
  109.       
  110.       
  111.     /** 
  112.      * @description: 将Map集合转换成Json字符串     
  113.      *      输出: 
  114.      *          jsonGenerator   {"name":"bugyun","account":{"id":1,"name":"bugyun","email":"bugyun@hotmail.com","address":"js_wuxi","birthday":null}} 
  115.      *          ObjectMapper    {"name":"bugyun","account":{"id":1,"name":"bugyun","email":"bugyun@hotmail.com","address":"js_wuxi","birthday":null}} 
  116.      * @return void     
  117.      * @throws 
  118.      * @author beyond 
  119.      * @data:2016年2月24日上午11:41:48 
  120.      */  
  121.     @Test  
  122.     public void writeMapJSON() {  
  123.         try {  
  124.             Map<String, Object> map = new HashMap<String, Object>();  
  125.             map.put("name", bean.getName());  
  126.             map.put("account", bean);  
  127.   
  128.             System.out.println("jsonGenerator");  
  129.             jsonGenerator.writeObject(map);  
  130.   
  131.             System.out.println("\n ObjectMapper");  
  132.             objectMapper.writeValue(System.out, map);  
  133.         } catch (IOException e) {  
  134.             e.printStackTrace();  
  135.         }  
  136.     }  
  137.       
  138.       
  139.     /** 
  140.      *  
  141.      * @description: 将List集合转换成json  
  142.      *  外面就是多了个[]中括号;同样Array也可以转换,转换的JSON和上面的结果是一样的 
  143.      *    输出: 
  144.      *      jsonGenerator   [{"id":1,"name":"bugyun","email":"bugyun@hotmail.com","address":"js_wuxi","birthday":null}] 
  145.      *      ObjectMapper    1###[{"id":1,"name":"bugyun","email":"bugyun@hotmail.com","address":"js_wuxi","birthday":null}] 
  146.      *                      2###[{"id":1,"name":"bugyun","email":"bugyun@hotmail.com","address":"js_wuxi","birthday":null}] 
  147.      * @return void     
  148.      * @throws 
  149.      * @author beyond 
  150.      * @data:2016年2月24日上午11:46:41 
  151.      */  
  152.     @Test  
  153.     public void writeListJSON() {  
  154.         try {  
  155.             List<AccountBean> list = new ArrayList<AccountBean>();  
  156.             list.add(bean);  
  157.               
  158.             System.out.println("jsonGenerator");  
  159.             jsonGenerator.writeObject(list);  
  160.               
  161.             System.out.println("\nObjectMapper");  
  162.             System.out.println("1###" + objectMapper.writeValueAsString(list));  
  163.               
  164.             System.out.print("2###");  
  165.             objectMapper.writeValue(System.out, list);  
  166.         } catch (IOException e) {  
  167.             e.printStackTrace();  
  168.         }  
  169.     }  
  170.   
  171.       
  172.     /** 
  173.      * @description: 复杂的Java类型的JSON转换     
  174.      *      输出: 
  175.      *          {"user":{"name":"jackson","sex":true,"age":22},"infos":[22,"this is array"]}  
  176.      *          {"user":{"id":1,"name":"haha","email":"email","address":"address","birthday":null},"infos":["a","b","c"]} 
  177.      * @return void     
  178.      * @throws 
  179.      * @author beyond 
  180.      * @data:2016年2月24日下午1:08:06 
  181.      */  
  182.     @Test  
  183.     public void writeOthersJSON() {  
  184.         try {  
  185.             String[] arr = { "a", "b", "c" };  
  186.             //Object  
  187.             jsonGenerator.writeStartObject();//{  
  188.             jsonGenerator.writeObjectFieldStart("user");//user:{  
  189.             jsonGenerator.writeStringField("name", "jackson");//name:jackson  
  190.             jsonGenerator.writeBooleanField("sex", true);//sex:true  
  191.             jsonGenerator.writeNumberField("age", 22);//age:22  
  192.             jsonGenerator.writeEndObject();//}  
  193.               
  194.             jsonGenerator.writeArrayFieldStart("infos");//infos:[  
  195.             jsonGenerator.writeNumber(22);//22  
  196.             jsonGenerator.writeString("this is array");//this is array  
  197.             jsonGenerator.writeEndArray();//]  
  198.               
  199.             jsonGenerator.writeEndObject();//}  
  200.               
  201. //          ********************************************  
  202.             AccountBean bean = new AccountBean();  
  203.             bean.setAddress("address");  
  204.             bean.setEmail("email");  
  205.             bean.setId(1);  
  206.             bean.setName("haha");  
  207.             jsonGenerator.writeStartObject();//{  
  208.             jsonGenerator.writeObjectField("user", bean);//user:{bean}  
  209.             jsonGenerator.writeObjectField("infos", arr);//infos:[array]  
  210.             jsonGenerator.writeEndObject();//}  
  211.   
  212.         } catch (Exception e) {  
  213.             e.printStackTrace();  
  214.         }  
  215.     }  
  216.       
  217.       
  218.     /** 
  219.      * @description: 将json字符串转换成JavaBean对象    
  220.      *      用到了ObjectMapper这个对象的readValue这个方法,这个方法需要提供2个参数。 
  221.      *      第一个参数就是解析的JSON字符串, 
  222.      *      第二个参数是将这个JSON解析持什么Java对象,Java对象的类型。当然,还有其他相同签名方法。 
  223.      *       
  224.      *      输出: 
  225.      *          haha 
  226.      *          haha#1#address#null#email 
  227.      * @return void     
  228.      * @throws 
  229.      * @author beyond 
  230.      * @data:2016年2月24日下午3:37:50 
  231.      */  
  232.     @Test  
  233.     public void readJson2Entity() {  
  234.         String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";  
  235.         try {  
  236.             AccountBean acc = objectMapper.readValue(json, AccountBean.class);  
  237.             System.out.println(acc.getName());  
  238.             System.out.println(acc);  
  239.         } catch (JsonParseException e) {  
  240.             e.printStackTrace();  
  241.         } catch (JsonMappingException e) {  
  242.             e.printStackTrace();  
  243.         } catch (IOException e) {  
  244.             e.printStackTrace();  
  245.         }  
  246.     }  
  247.       
  248.       
  249.     /** 
  250.      * @description: json字符串转换成list<map>  
  251.      *      输出: 
  252.      *          address:address2 
  253.      *          name:haha2 
  254.      *          id:2 
  255.      *          email:email2 
  256.      *          address:address 
  257.      *          name:haha 
  258.      *          id:1 
  259.      *          email:email 
  260.      * @return void     
  261.      * @throws 
  262.      * @author beyond 
  263.      * @data:2016年2月25日下午4:39:39 
  264.      */  
  265.     @Test  
  266.     public void readJson2List() {  
  267.         String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"  
  268.                 + "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";  
  269.         try {  
  270.             List<Map<String, Object>> list = objectMapper.readValue(json, List.class);  
  271. //          System.out.println(list.size());  
  272.             for (int i = 0; i < list.size(); i++) {  
  273.                 Map<String, Object> map = list.get(i);  
  274.                 Set<String> set = map.keySet();  
  275.                 for (Iterator it = set.iterator(); it.hasNext();) {  
  276.                     String key = (String) it.next();  
  277.                     System.out.println(key + ":" + map.get(key));  
  278.                 }  
  279.             }  
  280.         } catch (JsonParseException e) {  
  281.             e.printStackTrace();  
  282.         } catch (JsonMappingException e) {  
  283.             e.printStackTrace();  
  284.         } catch (IOException e) {  
  285.             e.printStackTrace();  
  286.         }  
  287.     }  
  288.       
  289.       
  290.     /** 
  291.      *  
  292.      * @description: json字符串转换成Array  
  293.      *      输出: 
  294.      *          haha2#2#address2#null#email2 
  295.      *          haha#1#address#null#email    
  296.      * @return void     
  297.      * @throws 
  298.      * @author beyond 
  299.      * @data:2016年2月25日下午4:44:09 
  300.      */  
  301.     @Test  
  302.     public void readJson2Array() {  
  303.         String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"  
  304.                 + "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";  
  305.         try {  
  306.             AccountBean[] arr = objectMapper.readValue(json, AccountBean[].class);  
  307. //          System.out.println(arr.length);  
  308.             for (int i = 0; i < arr.length; i++) {  
  309.                 System.out.println(arr[i]);  
  310.             }  
  311.   
  312.         } catch (JsonParseException e) {  
  313.             e.printStackTrace();  
  314.         } catch (JsonMappingException e) {  
  315.             e.printStackTrace();  
  316.         } catch (IOException e) {  
  317.             e.printStackTrace();  
  318.         }  
  319.     }  
  320.       
  321.       
  322.     /** 
  323.      *  
  324.      * @description: json字符串转换Map集合     
  325.      *      输出: 
  326.      *          success:true 
  327.      *          A:{address=address2, name=haha2, id=2, email=email2} 
  328.      *          B:{address=address, name=haha, id=1, email=email} 
  329.      * @return void     
  330.      * @throws 
  331.      * @author beyond 
  332.      * @data:2016年2月25日下午4:48:40 
  333.      */  
  334.     @Test  
  335.     public void readJson2Map() {  
  336.         String json = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"  
  337.                 + "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";  
  338.         try {  
  339.             Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);  
  340. //          System.out.println(maps.size());  
  341.             Set<String> key = maps.keySet();  
  342.             Iterator<String> iter = key.iterator();  
  343.             while (iter.hasNext()) {  
  344.                 String field = iter.next();  
  345.                 System.out.println(field + ":" + maps.get(field));  
  346.             }  
  347.         } catch (JsonParseException e) {  
  348.             e.printStackTrace();  
  349.         } catch (JsonMappingException e) {  
  350.             e.printStackTrace();  
  351.         } catch (IOException e) {  
  352.             e.printStackTrace();  
  353.         }  
  354.     }  
  355.       
  356.       
  357.       
  358.     /** 
  359.      * @description: java Object 转换为 xml 
  360.      *      输出: 
  361.      *          <ArrayList xmlns=""><item><id>1</id><name>bugyun</name><email>bugyun@hotmail.com</email><address>js_wuxi</address><birthday/></item></ArrayList> 
  362.      *          <HashMap xmlns=""><A><id>1</id><name>bugyun</name><email>bugyun@hotmail.com</email><address>js_wuxi</address><birthday/></A></HashMap> 
  363.      * @return void     
  364.      * @throws 
  365.      * @author beyond 
  366.      * @data:2016年2月26日上午9:20:49 
  367.      */  
  368.     @Test  
  369.     public void writeObject2Xml() {  
  370.         XmlMapper xml = new XmlMapper();  
  371.           
  372.         try {  
  373.             //javaBean转换成xml  
  374.             //xml.writeValue(System.out, bean);  
  375.             StringWriter sw = new StringWriter();  
  376.             xml.writeValue(sw, bean);  
  377. //          System.out.println(sw.toString());  
  378. //          List转换成xml  
  379.             List<AccountBean> list = new ArrayList<AccountBean>();  
  380.             list.add(bean);  
  381.             System.out.println(xml.writeValueAsString(list));  
  382.               
  383. //          Map转换xml文档  
  384.             Map<String, AccountBean> map = new HashMap<String, AccountBean>();  
  385.             map.put("A", bean);  
  386.             System.out.println(xml.writeValueAsString(map));  
  387.         } catch (JsonGenerationException e) {  
  388.             e.printStackTrace();  
  389.         } catch (JsonMappingException e) {  
  390.             e.printStackTrace();  
  391.         } catch (IOException e) {  
  392.             e.printStackTrace();  
  393.         }  
  394.     }  
  395.       
  396. }  

 

引用原文:http://bugyun.iteye.com/blog/2278997

 

写博客是为了记住自己容易忘记的东西,另外也是对自己工作的总结,文章可以转载,无需版权。希望尽自己的努力,做到更好,大家一起努力进步!

如果有什么问题,欢迎大家一起探讨,代码如有问题,欢迎各位大神指正!

Jackson 框架JSON、XML、List、Map直接相互转换

标签:res   忘记   use   输出流   cti   xmlns   java   archive   trace   

原文地址:https://www.cnblogs.com/summary-2017/p/8965042.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!