`

jackson处理json对象相关小结

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

1 JAVA 对象转为JSON
 

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
public class JacksonExample {
    public static void main(String[] args) {
 
	User user = new User();
	ObjectMapper mapper = new ObjectMapper();
 
	try {
 
		// convert user object to json string, and save to a file
		mapper.writeValue(new File("c:\\user.json"), user);
 
		// display to console
		System.out.println(mapper.writeValueAsString(user));
 
	} catch (JsonGenerationException e) {
 
		e.printStackTrace();
 
	} catch (JsonMappingException e) {
 
		e.printStackTrace();
 
	} catch (IOException e) {
 
		e.printStackTrace();
 
	}
 
  }
 



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


2 JSON反序列化为JAVA对象
  
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
public class JacksonExample {
    public static void main(String[] args) {
 
	ObjectMapper mapper = new ObjectMapper();
 
	try {
 
		// read from file, convert it to user class
		User user = mapper.readValue(new File("c:\\user.json"), User.class);
 
		// display to console
		System.out.println(user);
 
	} catch (JsonGenerationException e) {
 
		e.printStackTrace();
 
	} catch (JsonMappingException e) {
 
		e.printStackTrace();
 
	} catch (IOException e) {
 
		e.printStackTrace();
 
	}
 
  }
 


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

3 在上面的例子中,如果要输出的JSON好看点,还是有办法的,就是使用
defaultPrettyPrintingWriter()方法,例子为:
 User user = new User();
   ObjectMapper mapper = new ObjectMapper();
   System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(user));


则输出整齐:
{
  "age" : 29,
  "messages" : [ "msg 1", "msg 2", "msg 3" ],
  "name" : "mkyong"
}
 
8
5
分享到:
评论
1 楼 xiaowangzaixian 2011-10-26  
如果把这些处理方法封装在发布就可以了

相关推荐

Global site tag (gtag.js) - Google Analytics