1. 程式人生 > >jackson實現json資料與物件, 集合之間的轉換

jackson實現json資料與物件, 集合之間的轉換

     前面列舉了Gson和fastjson處理json格式資料的具體用法,以下介紹jackson如何簡單處理json格式資料,還是延用前面文章中的實體類Product.

 

 

     使用jackson需要引入以下第三方jar包:

 

package Exercise1_jackson;

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author huangxinyi
 * jackson實現物件和json,集合和json之間的互相轉換
 * 
 */
public class Test {
	
	private ObjectMapper objectMapper = new ObjectMapper();
	
	@org.junit.Test
	public void test(){
		String jsonArr = "[{\"brand\":\"聯想\",\"type\":\"電腦\",\"color\":\"白色\",\"price\":\"3000\"},"+
                "{\"brand\":\"小米\",\"type\":\"手機\",\"color\":\"黑色\",\"price\":\"2500\"},"+
                "{\"brand\":\"華為\",\"type\":\"手機\",\"color\":\"白色\",\"price\":\"2000\"},"+
                "{\"brand\":\"戴爾\",\"type\":\"電腦\",\"color\":\"藍色\",\"price\":\"4000\"},"+
                "{\"brand\":\"蘋果\",\"type\":\"手機\",\"color\":\"紅色\",\"price\":\"5000\"}]";
			
		try {
			//json轉集合
			List<Product> plist = objectMapper.readValue(jsonArr, new TypeReference<List<Product>>(){});
			System.out.println(plist);
			
			//json轉物件
			Product p = objectMapper.readValue("{\"brand\":\"小米\",\"type\":\"手機\",\"color\":\"黑色\",\"price\":\"2500\"}", Product.class);
			System.out.println(p);
			
			//物件轉json
			String json_p = objectMapper.writeValueAsString(new Product("小米","手機","黑色",2500));
			System.out.println(json_p);
			
			//集合轉json
			String json_list = objectMapper.writeValueAsString(plist);
			System.out.println(json_list);
			
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}