1. 程式人生 > >json物件互轉

json物件互轉

import java.io.IOException;
import java.io.StringWriter;


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


/**
 * 將物件轉json,json轉物件
 * 
 * @author pan
 * 
 */
public class JsonUtil {


public static String obj2Json(Object obj) {


StringWriter stringWriter = new StringWriter();
JsonGenerator jsonGenerator = null;
try {
jsonGenerator = new JsonFactory().createJsonGenerator(stringWriter);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(jsonGenerator, obj);
} catch (IOException e) {
// TODO 記錄日誌
e.printStackTrace();
} finally {
if (null != jsonGenerator) {
try {
jsonGenerator.close();
} catch (IOException e) {
// TODO 記錄日誌
e.printStackTrace();
}
}
}
return stringWriter.getBuffer().toString();
}


public static <T> T json2Obj(String json, Class<T> cls) {


ObjectMapper mapper = new ObjectMapper();
T o = null;
try {
o = mapper.readValue(json, cls);
return o;
} catch (Exception e) {
e.printStackTrace();
}
return o;
}
}