package com.bocom.framework.util;
import java.io.IOException;
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 JsonFactory jsonfactory = new JsonFactory();
private static ObjectMapper objectmapper = new ObjectMapper();
//对象转json字符串
public static String object2Json(Object object) throws IOException
{
if(object==null) return null;
String result = null;
JsonGenerator jg = null;
StringWriter sw = null;
try
{
sw = new StringWriter();
jg = jsonfactory.createJsonGenerator(sw);
objectmapper.writeValue(jg, object);
result = sw.toString();
}
catch (IOException e)
{
jg.flush();
}
finally
{
if(sw != null) sw.close();
if(jg != null) jg.close();
}
return result;
}
//json字符串转对象
public static <T> T json2Object(String jsonStr,Class<T> c)
{
T obj = null;
try
{
obj = objectmapper.readValue(jsonStr, c);
}
catch (Exception e)
{
e.printStackTrace();
}
return obj;
}
}