jackson处理json对象相关小结

jackson处理json对象相关小结 - jackyrong - ITeye技术网站

在解析JSON方面,无疑JACKSON是做的最好的,下面从几个方面简单复习下。



1 JAVA 对象转为JSON

 
Java代码  收藏代码
  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import org.codehaus.jackson.JsonGenerationException;  
  4. import org.codehaus.jackson.map.JsonMappingException;  
  5. import org.codehaus.jackson.map.ObjectMapper;  
  6.    
  7. public class JacksonExample {  
  8.     public static void main(String[] args) {  
  9.    
  10.     User user = new User();  
  11.     ObjectMapper mapper = new ObjectMapper();  
  12.    
  13.     try {  
  14.    
  15.         // convert user object to json string, and save to a file  
  16.         mapper.writeValue(new File("c:\\user.json"), user);  
  17.    
  18.         // display to console  
  19.         System.out.println(mapper.writeValueAsString(user));  
  20.    
  21.     } catch (JsonGenerationException e) {  
  22.    
  23.         e.printStackTrace();  
  24.    
  25.     } catch (JsonMappingException e) {  
  26.    
  27.         e.printStackTrace();  
  28.    
  29.     } catch (IOException e) {  
  30.    
  31.         e.printStackTrace();  
  32.    
  33.     }  
  34.    
  35.   }  
  36.    




输出为:

{"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"mkyong"}





2 JSON反序列化为JAVA对象

  

Java代码  收藏代码
  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import org.codehaus.jackson.JsonGenerationException;  
  4. import org.codehaus.jackson.map.JsonMappingException;  
  5. import org.codehaus.jackson.map.ObjectMapper;  
  6.    
  7. public class JacksonExample {  
  8.     public static void main(String[] args) {  
  9.    
  10.     ObjectMapper mapper = new ObjectMapper();  
  11.    
  12.     try {  
  13.    
  14.         // read from file, convert it to user class  
  15.         User user = mapper.readValue(new File("c:\\user.json"), User.class);  
  16.    
  17.         // display to console  
  18.         System.out.println(user);  
  19.    
  20.     } catch (JsonGenerationException e) {  
  21.    
  22.         e.printStackTrace();  
  23.    
  24.     } catch (JsonMappingException e) {  
  25.    
  26.         e.printStackTrace();  
  27.    
  28.     } catch (IOException e) {  
  29.    
  30.         e.printStackTrace();  
  31.    
  32.     }  
  33.    
  34.   }  
  35.    


输出:User [age=29, name=mkyong, messages=[msg 1, msg 2, msg 3]]



3 在上面的例子中,如果要输出的JSON好看点,还是有办法的,就是使用

defaultPrettyPrintingWriter()方法,例子为:


Java代码  收藏代码
  1. User user = new User();  
  2.   ObjectMapper mapper = new ObjectMapper();  
  3.   System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(user));  




则输出整齐:

{

  "age" : 29,

  "messages" : [ "msg 1", "msg 2", "msg 3" ],

  "name" : "mkyong"

}

 

原文地址:https://www.cnblogs.com/lexus/p/2611657.html