使用Jackson转换JavaBean遇到的问题

    今天想试一下Jackson与JavaBean之间的相互转换效果,写了个简单的例子,如下所示:

   

package com.huse.java.xmljson;
import java.util.Date;
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;

 public class DateBeanTest {
	public String toString() {
		return "DateBeanTest [name=" + name + ", sqlDate="
				+ sqlDate.toLocaleString() + ", ctime="
				+ ctime.toLocaleString() + "]";
	}

	private String name;
	private java.sql.Date sqlDate;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public DateBeanTest(String name, java.sql.Date sqlDate, Date ctime) {
		super();
		this.name = name;
		this.sqlDate = sqlDate;
		this.ctime = ctime;
	}

	public DateBeanTest() {
		super();
	}

	@JsonDeserialize(using = CustomSqlDateDeSerializer.class)
	public void setSqlDate(java.sql.Date sqlDate) {
		this.sqlDate = sqlDate;
	}

	@JsonDeserialize(using = CustomUtilDateDeSerializer.class)
	public void setCtime(Date ctime) {
		this.ctime = ctime;
	}

	private Date ctime;

	@JsonSerialize(using = CustomUtilDateSerializer.class)
	public Date getCtime() {
		return ctime;
	}

	@JsonSerialize(using = CustomSqlDateSerializer.class)
	public java.sql.Date getSqlDate() {
		return sqlDate;
	}
}

    转换器如下:

package com.huse.java.xmljson;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

/**
 * java日期对象经过Jackson库转换成JSON日期格式化自定义类
 * 
 * @author godfox
 * @date 2010-5-3
 */
public class CustomUtilDateSerializer extends JsonSerializer<Date> {

	public void serialize(Date value, JsonGenerator jgen,
			SerializerProvider provider) throws IOException,
			JsonProcessingException {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String formattedDate = formatter.format(value);
		jgen.writeString(formattedDate);
	}

}

  

package com.huse.java.xmljson;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

public class CustomUtilDateDeSerializer extends JsonDeserializer<Date> {
	public Date deserialize(JsonParser jsonparser,
			DeserializationContext deserializationcontext) throws IOException,
			JsonProcessingException {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = formatter.parse(jsonparser.getText());
		} catch (ParseException e) {
			date = new Date(jsonparser.getLongValue());
		}
		return date;
	}
}

   Jackson转换JavaBean方法如下:

  

package com.huse.java.xmljson;

import java.io.StringWriter;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonHelper {
	private static JacksonHelper jsonUtil;
	private static JsonFactory jsonFactory;
	private static ObjectMapper objectMapper;

	private JacksonHelper() {

	}

	public static JacksonHelper getInstance() {
		if (jsonUtil == null)
			jsonUtil = new JacksonHelper();
		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 void obj2jsonSysOut(Object obj) {
		JsonGenerator jsonGenerator = null;
		JsonFactory jf = null;
		try {
			objectMapper = getMapper();
			//StringWriter out = new StringWriter();
			jf = objectMapper.getJsonFactory();
			jsonGenerator = jf.createJsonGenerator(System.out,
					JsonEncoding.UTF8);
			objectMapper.writeValue(jsonGenerator, obj);
			//jsonGenerator = jf.createJsonGenerator(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (jsonGenerator != null) {
					jsonGenerator.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public String obj2json(Object obj) {
		try {
			objectMapper = getMapper();
			return objectMapper.writeValueAsString(obj);
		} catch (Exception e) {
			e.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;
	}

}

 

   测试方法为:

 

package com.huse.java.xmljson;

import java.util.Date;

public class JacksonDateBeanTest {
	public static void main(String[] args) {
		DateBeanTest t1=new DateBeanTest("test", new java.sql.Date(System.currentTimeMillis()), new Date());
		JacksonHelper jHelper=JacksonHelper.getInstance();
	    jHelper.obj2jsonSysOut(t1);
	    System.out.println();
		String str=jHelper.obj2json(t1);
		DateBeanTest t3=(DateBeanTest) jHelper.json2obj(str, DateBeanTest.class);
		System.out.println(t3);
	}
}

 

     运行结果为:

{"name":"test","sqlDate":"2013-12-26","ctime":"2013-12-26"}

     很奇怪,为什么没打印Json转换为JavaBean的结果,试着打了几个断点看下,发现程序正常运行结束,没有中途出错,开始怀疑是不是使用了静态变量设置System.out输出后没改回来,修改代码为:

   

public void obj2jsonSysOut(Object obj) {
		JsonGenerator jsonGenerator = null;
		JsonFactory jf = null;
		try {
			objectMapper = getMapper();
			StringWriter out = new StringWriter();
			jf = objectMapper.getJsonFactory();
			jsonGenerator = jf.createJsonGenerator(System.out,
					JsonEncoding.UTF8);
			objectMapper.writeValue(jsonGenerator, obj);
			jsonGenerator = jf.createJsonGenerator(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (jsonGenerator != null) {
					jsonGenerator.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

    运行结果为:

    

{"name":"test","sqlDate":"2013-12-26","ctime":"2013-12-26"}
DateBeanTest [name=test, sqlDate=2013-12-26 0:00:00, ctime=2013-12-26 0:00:00]

   ps,但我obj2json设置输出为StringWrite为什么没起作用呢?

 

 

 

 

你可能感兴趣的:(javabean)