jackson处理json对象相关小结

来源:互联网 发布:mac 窗口跨两屏幕 编辑:程序博客网 时间:2024/05/20 22:30
在解析JSON方面,无疑JACKSON是做的最好的,下面从几个方面简单复习下。

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


输出为:
{"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"