Java開発でjavaオブジェクトとjson文字列の相互変換サンプルコード

Javaコード:
import java.io.IOException;
import java.io.StringWriter;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {

private static JacksonUtil ju;
private static JsonFactory jf;
private static ObjectMapper mapper;
private JacksonUtil(){}

/**
* 单例初始化
* @Title: newInstance
* @Description: TODO
* @param @return
* @return JacksonUtil
* @throws
*/
public static JacksonUtil newInstance() {
if(ju==null) ju = new JacksonUtil();
return ju;
}

public static ObjectMapper getMapper() {
if(mapper==null) {
mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
return mapper;
}

public static JsonFactory getFactory() {
if(jf==null) jf = new JsonFactory();
return jf;
}
/**
*
* @Title: obj2json
* @Description: オブジェクト->json文字列
* @param @param obj
* @param @return
* @return String
* @throws
*/
public String obj2json(Object obj) {
if(null != obj){
JsonGenerator jg = null;
try {
jf = getFactory();
mapper = getMapper();
StringWriter out = new StringWriter();
jg = jf.createJsonGenerator(out);
mapper.writeValue(jg, obj);
return out.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(jg!=null) jg.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
*
* @Title: json2obj
* @Description: json文字列からjavaオブジェクトに変換
* @param @param json
* @param @param clz
* @param @return
* @return Object
* @throws
*/
public <E>E json2obj(String json,Class<E> clz) {
if(null != json && !"".equals(json.trim())){
try {
mapper = getMapper();
return mapper.readValue(json,clz);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}

Java

Posted by arkgame