使用jackson生成json对象的实例_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 使用jackson生成json对象的实例

使用jackson生成json对象的实例

 2013/10/24 12:53:14  alleni123  程序员俱乐部  我要评论(0)
  • 摘要:packagecom.lj.basic.util;importjava.io.StringWriter;importcom.fasterxml.jackson.core.JsonFactory;importcom.fasterxml.jackson.core.JsonGenerator;importcom.fasterxml.jackson.databind.ObjectMapper;publicclassJsonUtil{privatestaticJsonUtiljsonUtil
  • 标签:使用 实例 JSON JS
class="java">package com.lj.basic.util;

import java.io.StringWriter;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
	private static JsonUtil jsonUtil;
	private static JsonFactory jsonFactory;
	private static ObjectMapper objectMapper;
	private JsonUtil(){
		
	}
	
	public static JsonUtil getInstance(){
		if(jsonUtil==null) jsonUtil=new JsonUtil();
		return jsonUtil;
	}
	
	public static ObjectMapper getMapper(){
		if(objectMapper == null){
			objectMapper=new ObjectMapper();
		}
		return objectMapper;
	}
	
	public static JsonFactory getFactory(){
		if(jsonFactory==null) jsonFactory=new JsonFactory();
		return jsonFactory;
	}
	
	public String obj2json(Object obj){
		JsonGenerator jsonGenerator = null;
		try {
			jsonFactory=getFactory();
			objectMapper=getMapper();
			StringWriter out = new StringWriter();
			jsonGenerator = jsonFactory.createGenerator(out);
			objectMapper.writeValue(jsonGenerator, obj);
			return out.toString();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			try {
				if(jsonGenerator!=null)jsonGenerator.close();
			} catch (Exception e2) {
				 e2.printStackTrace();
			}
		}
		
		return null;
	}

	
	public Object json2obj(String json, Class<?> clz){
		try {
			objectMapper=getMapper();
			return objectMapper.readValue(json, clz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	

}



发表评论
用户名: 匿名