使用Jackson在Java中处理JSON

        在工作中实际使用到Java处理JSON的情况,且有很大部分都使用的是开源工具Jackson实现的。

一.入门

        Jackson中有个ObjectMapper类很是实用,用于Java对象与JSON的互换。

1.Java对象转换为JSON

Java代码  收藏代码
  1. Student st=new Student(); //Java Object  
  2. ObjectMapper mapper = new ObjectMapper();  
  3. java.text.DateFormat myFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  4. mapper.getSerializationConfig().setDateFormat(myFormat);  
  5. try {  
  6.     //返回字符串  
  7.     String res = mapper.writeValueAsString(st);  
  8.     System.out.println(res);  
  9.       
  10.     //输出格式化后的字符串(有性能损耗)  
  11.     res = mapper.defaultPrettyPrintingWriter().writeValueAsString(st);  
  12.     System.out.println(res);  
  13.       
  14.     mapper.writeValue(new File("D:\st.json"), st); //指定文件写入  
  15.        
  16.     //设置序列化配置(全局),设置序列化时不输出空值.  
  17.     mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);  
  18.       
  19.     res = mapper.writeValueAsString(st);  
  20.     System.out.println(res);  
  21. catch (Exception e) {  
  22.     e.printStackTrace();  
  23. }  

2.JSON反序列化为Java对象

Java代码  收藏代码
  1. String json = "{"error":0,"data":{"name":"ABC","age":20,"phone":{"home":"abc","mobile":"def"},"friends":[{"name":"DEF","phone":{"home":"hij","mobile":"klm"}},{"name":"GHI","phone":{"home":"nop","mobile":"qrs"}}]},"other":{"nickname":[]}}";  
  2. ObjectMapper mapper = new ObjectMapper();  
  3. //解析器支持解析单引号  
  4. mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);  
  5. //解析器支持解析结束符  
  6. mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);  
  7. try {  
  8.     //转换为HashMap对象  
  9.     HashMap jsonMap = mapper.readValue(json, HashMap.class);  
  10.     Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);  
  11.     System.out.println(maps.get("error"));//0  
  12.     System.out.println((Object) (maps.get("data").get("phone")));//{home=abc, mobile=def}  
  13. catch (Exception e) {  
  14.     e.printStackTrace();  
  15. }  

二.Jackson支持三种使用方式

1.Data Binding:最方便使用

(1)Full Data Binding

Java代码  收藏代码
  1. /* 
  2.  * Full Data Binding 
  3.  */  
  4. public static void fullDataBinding() {  
  5.   
  6.     ObjectMapper mapper = new ObjectMapper();  
  7.     try {  
  8.         Model model = mapper.readValue(MODEL_BINDING, Model.class);  
  9.         //readValue到一个实体类中.    
  10.         System.out.println(model.getName()); //name1   
  11.         System.out.println(model.getType()); //1  
  12.     } catch (Exception e) {  
  13.         e.printStackTrace();  
  14.     }  
  15. }  
  16.   
  17. private static class Model {  
  18.     private String name;  
  19.     private int type;  
  20.   
  21.     public String getName() {  
  22.         return name;  
  23.     }  
  24.   
  25.     public void setName(String name) {  
  26.         this.name = name;  
  27.     }  
  28.   
  29.     public int getType() {  
  30.         return type;  
  31.     }  
  32.   
  33.     public void setType(int type) {  
  34.         this.type = type;  
  35.     }  
  36. }  

(2)Raw Data Binding

Java代码  收藏代码
  1. /* 
  2.  * Raw Data Binding 
  3.  */  
  4. public static void rawDataBinding() {  
  5.     ObjectMapper mapper = new ObjectMapper();  
  6.     try {  
  7.         HashMap map = mapper.readValue(MODEL_BINDING, HashMap.class);//readValue到一个原始数据类型.    
  8.         System.out.println(map.get("name")); //name1  
  9.         System.out.println(map.get("type")); //1  
  10.     } catch (Exception e) {  
  11.         e.printStackTrace();  
  12.     }  
  13. }  

(3)generic Data Binding

Java代码  收藏代码
  1. /* 
  2.  * generic Data Binding 
  3.  */  
  4. public static void genericDataBinding() {  
  5.       
  6.     ObjectMapper mapper = new ObjectMapper();  
  7.     try {  
  8.         HashMap<String, Model> modelMap = mapper.readValue(GENERIC_BINDING,  
  9.                 new TypeReference<HashMap<String, Model>>() {  
  10.                 });//readValue到一个范型数据中.    
  11.         Model model = modelMap.get("key2");  
  12.         System.out.println(model.getName()); //name3  
  13.         System.out.println(model.getType()); //3  
  14.     } catch (Exception e) {  
  15.         e.printStackTrace();  
  16.     }  
  17. }  

2.Tree Model:最灵活

Java代码  收藏代码
  1. /* 
  2.  * Tree Model:最灵活 
  3.  */  
  4. public static void treeModelBinding() {  
  5.     ObjectMapper mapper = new ObjectMapper();  
  6.     try {  
  7.         JsonNode rootNode = mapper.readTree(TREE_MODEL_BINDING);  
  8.         //path与get作用相同,但是当找不到该节点的时候,返回missing node而不是Null.    
  9.         String treekey2value = rootNode.path("treekey2").getTextValue();//    
  10.         System.out.println("treekey2value:" + treekey2value);  
  11.         JsonNode childrenNode = rootNode.path("children");  
  12.         String childkey1Value = childrenNode.get(0).path("childkey1").getTextValue();  
  13.         System.out.println("childkey1Value:" + childkey1Value);  
  14.   
  15.         //创建根节点    
  16.         ObjectNode root = mapper.createObjectNode();  
  17.         //创建子节点1    
  18.         ObjectNode node1 = mapper.createObjectNode();  
  19.         node1.put("nodekey1"1);  
  20.         node1.put("nodekey2"2);  
  21.         //绑定子节点1    
  22.         root.put("child", node1);  
  23.         //数组节点    
  24.         ArrayNode arrayNode = mapper.createArrayNode();  
  25.         arrayNode.add(node1);  
  26.         arrayNode.add(1);  
  27.         //绑定数组节点    
  28.         root.put("arraynode", arrayNode);  
  29.         //JSON读到树节点    
  30.         JsonNode valueToTreeNode = mapper.valueToTree(TREE_MODEL_BINDING);  
  31.         //绑定JSON节点    
  32.         root.put("valuetotreenode", valueToTreeNode);  
  33.         //JSON绑定到JSON节点对象    
  34.         JsonNode bindJsonNode = mapper.readValue(GENERIC_BINDING, JsonNode.class);//绑定JSON到JSON节点对象.    
  35.         //绑定JSON节点    
  36.         root.put("bindJsonNode", bindJsonNode);  
  37.         System.out.println(mapper.writeValueAsString(root));  
  38.     } catch (Exception e) {  
  39.         e.printStackTrace();  
  40.     }  
  41. }  

3.Streaming API。最佳性能

见官方文档例子。

进一步学习资料:

1.http://wiki.fasterxml.com/JacksonInFiveMinutes Jackson官方教程示例

2.http://wiki.fasterxml.com/JacksonJavaDocs Jackson在线API文档

3.http://hjg1988.iteye.com/blog/561368 JSON工具性能比较:json-lib和jackson进行Java对象到json字符串序列化。

文章来源:http://shensy.iteye.com/blog/1717776

原文地址:https://www.cnblogs.com/jpfss/p/9055747.html