同时Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。功能非常的强悍!

       大家也知道,json 在如今互联网时代应用的非常广,因为大家如此的关注,所以对json的解析性能要求也是非常高的。

 

一、 准备工作

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、 测试类基本代码如下

 

[java] view plaincopy
 
  1.  
  2. public class Jackson {  
  3.     public  static JsonGenerator jsonGenerator = null;  
  4.     private static ObjectMapper mapper = new ObjectMapper();  
  5.     public static void main(String[] args) {  
  6.         Student student = new Student();  
  7.         student.setIsstudent(true);  
  8.         student.setUid(1000);  
  9.         student.setUname("xiao liao");  
  10.         student.setUpwd("123");  
  11.         student.setNumber(12);  
  12.           
  13.         Map<String, Student> stuMap = new HashMap<String, Student>();  
  14.         stuMap.put("1", student);  
  15.         stuMap.put("2", student);  
  16.           
  17.         List<Object> stuList = new ArrayList<Object>();  
  18.         List<Student> stuList1 = new ArrayList<Student>();  
  19.         stuList1.add(student);  
  20.         student=  new  Student();  
  21.         student.setIsstudent(false);  
  22.         student.setUid(200);  
  23.         student.setUname("xiao mi");  
  24.         stuList1.add(student);  
  25.           
  26.         stuList.add(student);  
  27.         stuList.add("xiao xin");  
  28.         stuList.add("xiao er");  
  29.         stuList.add(stuMap);  
  30.           
  31.         //readJson2List();  
  32.         try {  
  33.             //readJson2Array();  
  34.             //writeArray2Json(array);  
  35.             //writeJson2List();  
  36.             //writeEntity2Json(student);  
  37.             writeJson2Entity();  
  38.             //writeMap2Json(stuMap);  
  39.             //writeList2Json(stuList1);  
  40.               
  41.         } catch (IOException e) {  
  42.             e.printStackTrace();  
  43.         }  
  44.     }  
  45.      
  46.      public static void writeEntity2Json(Object object) throws IOException {  
  47.            mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt"),object );  
  48.            mapper.writeValue( System.out,object );  
  49.            
  50.      }  
  51.   
  52.      public static void writeArray2Json(Object object) throws IOException {  
  53.            
  54.          // writeValue具有和writeObject相同的功能  
  55.          mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt"),object );  
  56.          mapper.writeValue(System.out,object );  
  57.            
  58.      }  
  59.      
  60.      public static void writeMap2Json(Object object) throws IOException {  
  61.            
  62.          System.out.println("使用ObjectMapper-----------");  
  63.          // writeValue具有和writeObject相同的功能  
  64.          System.out.println("==>"+mapper.writeValueAsString(object));  
  65.          mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aamap.txt"),object );  
  66.          mapper.writeValue( System.out , object );  
  67.      }  
  68.     
  69.      public static void writeList2Json(Object object) throws IOException {  
  70.          System.out.println("==>"+mapper.writeValueAsString(object));  
  71.          mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aamap.txt"),object );  
  72.          mapper.writeValue( System.out , object );  
  73.      }  
  74.    
  75.      public static void writeJson2Entity() throws IOException {  
  76.          System.out.println("json串转换成entity-------------");  
  77. //       File file = new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt");  
  78. //       FileInputStream inputStream = new FileInputStream(file);  
  79. //       Student student = mapper.readValue(inputStream,Student.class);  
  80. //       System.out.println(student.toString());  
  81.          //漂亮输出  
  82.          //mapper.defaultPrettyPrintingWriter().writeValueAsString(value);  
  83.       
  84.          String json = "{\"uid\":1000,\"uname\":\"xiao liao\",\"upwd\":\"123\",\"number\":12.0,\"isstudent\":true}";  
  85.          Student student1 = mapper.readValue(json,Student.class);  
  86.          System.out.println("json2:"+student1.toString());  
  87.      }  
  88.    
  89.      public static void writeJson2List() throws IOException {  
  90.          System.out.println("json串转换成entity-------------");  
  91.          File file = new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt");  
  92.          FileInputStream inputStream = new FileInputStream(file);  
  93.          Student student = mapper.readValue(inputStream,Student.class);  
  94.          System.out.println(student.toString());  
  95.            
  96.          String json = "[{\"uid\":1000,\"uname\":\"xiao liao\",\"upwd\":\"123\",\"number\":12.0,\"isstudent\":true},{\"uid\":200,\"uname\":\"xiao mi\",\"upwd\":null,\"number\":0.0,\"isstudent\":false}]";  
  97.          List<LinkedHashMap<String, Object>> s= mapper.readValue(json,List.class);  
  98.          for (int i = 0; i < s.size(); i++) {  
  99.              LinkedHashMap<String, Object> link = s.get(i);  
  100.              Set<String>  key = link.keySet();  
  101.              for (Iterator iterator = key.iterator(); iterator.hasNext();) {  
  102.                 String string = (String) iterator.next();  
  103.                 System.out.println(string+"==>"+link.get(string));  
  104.                   
  105.             }  
  106.              System.out.println("json:"+i+""+s.get(i).toString());  
  107.               
  108.         }  
  109.      }  
  110.      /** 
  111.        * JSON转换为List对象 
  112.        */  
  113.       public static void readJson2List() {  
  114.        String json = "[{\"uid\":1,\"uname\":\"www\",\"number\":234,\"upwd\":\"456\"},"  
  115.          + "{\"uid\":5,\"uname\":\"tom\",\"number\":3.44,\"upwd\":\"123\"}]";  
  116.        try {  
  117.         List<LinkedHashMap<String, Object>> list = mapper.readValue(  
  118.           json, List.class);  
  119.         System.out.println(list.size());  
  120.         for (int i = 0; i < list.size(); i++) {  
  121.          Map<String, Object> map = list.get(i);  
  122.          Set<String> set = map.keySet();  
  123.          for (Iterator<String> it = set.iterator(); it.hasNext();) {  
  124.           String key = it.next();  
  125.           System.out.println(key + ":" + map.get(key));  
  126.          }  
  127.         }  
  128.        } catch (JsonParseException e) {  
  129.         e.printStackTrace();  
  130.        } catch (JsonMappingException e) {  
  131.         e.printStackTrace();  
  132.        } catch (IOException e) {  
  133.         e.printStackTrace();  
  134.        }  
  135.       }  
  136.       /** 
  137.        * JSON转换为List对象 
  138.        */  
  139.       public static void readJson2Array() {  
  140.           String json = "[{\"uid\":1,\"uname\":\"www\",\"number\":234,\"upwd\":\"456\"},"  
  141.               + "{\"uid\":5,\"uname\":\"tom\",\"number\":3.44,\"upwd\":\"123\"}]";  
  142.           try {  
  143.               Student[] students = mapper.readValue(json, Student[].class);  
  144.               for (Student student : students) {  
  145.                 System.out.println(">"+student.toString());  
  146.             }  
  147.           } catch (JsonParseException e) {  
  148.               e.printStackTrace();  
  149.           } catch (JsonMappingException e) {  
  150.               e.printStackTrace();  
  151.           } catch (IOException e) {  
  152.               e.printStackTrace();  
  153.           }  
  154.       }  
  155.   
  156. }  

打印结果 :

串转换成entity-------------
json2:uid=1000,name=xiao liao,upwd=123,number=12.0,isStudent=true

writeMap2Json -----------
{"2":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true},"1":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true}}

readJson2Array------------------
>uid=1,name=www,upwd=456,number=234.0,isStudent=false
>uid=5,name=tom,upwd=123,number=3.44,isStudent=false
writeMap2Json -----------
{"2":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true},"1":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true}}

大家逐个自己试试吧  ,上面也是我的测试代码

 

[java] view plaincopy
 
    1. 实体类:  
    2. /* 
    3.  * @project java 
    4.  * @package  
    5.  * @file Student.java 
    6.  * @version  1.0 
    7.  * @author   廖益平 
    8.  * @time  2011-11-8 上午03:01:08 
    9.  */  
    10.   
    11. public class Student {  
    12.     /* 
    13.      * 
    14.      * Class Descripton goes here. 
    15.      * 
    16.      * @class Student 
    17.      * @version  1.0 
    18.      * @author   廖益平 
    19.      * @time  2011-11-8 上午03:01:08 
    20.      */  
    21.       private int uid;  
    22.       private String uname;  
    23.       private String upwd;  
    24.       private double number;  
    25.       private boolean isstudent;  
    26.     public int getUid() {  
    27.         return uid;  
    28.     }  
    29.     public void setUid(int uid) {  
    30.         this.uid = uid;  
    31.     }  
    32.     public String getUname() {  
    33.         return uname;  
    34.     }  
    35.     public void setUname(String uname) {  
    36.         this.uname = uname;  
    37.     }  
    38.     public String getUpwd() {  
    39.         return upwd;  
    40.     }  
    41.     public void setUpwd(String upwd) {  
    42.         this.upwd = upwd;  
    43.     }  
    44.     public double getNumber() {  
    45.         return number;  
    46.     }  
    47.     public void setNumber(double number) {  
    48.         this.number = number;  
    49.     }  
    50.     public boolean isIsstudent() {  
    51.         return isstudent;  
    52.     }  
    53.     public void setIsstudent(boolean isstudent) {  
    54.         this.isstudent = isstudent;  
    55.     }  
    56.     @Override  
    57.     public String toString() {  
    58.       
    59.         return "uid="+uid+",name="+uname+",upwd="+upwd+",number="+number+",isStudent="+isstudent;  
    60.     }  
    61.       
    62.         

         

            原文链接:http://blog.csdn.net/wangyang2698341/article/details/8223929

 

 

posted on 2017-05-27 10:08  孤峰侠客  阅读(237)  评论(0编辑  收藏  举报