public class JsonUtil {
private static JsonUtil ju;
private static JsonFactory jf;
private static ObjectMapper mapper;
private JsonUtil(){}
public static JsonUtil getInstance() {
if(ju==null) ju = new JsonUtil();
return ju;
}
public static ObjectMapper getMapper() {
if(mapper==null) {
mapper = new ObjectMapper();
}
return mapper;
}
public static JsonFactory getFactory() {
if(jf==null) jf = new JsonFactory();
return jf;
}
/**
* 将bean对象转换为json字符串,如obj可以为List
*
* /
public String obj2json(Object 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;
}
/**
* 将json数据转换为bean对象
*
* /
public Object json2obj(String json,Class<?> clz) {
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;
}
}
使用Jackson做对象与json之间的相互转换
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.