由于公司要与第三方接口进行对接,故有json字符串与JAVA对象相互转换的场景,特此记录。~~~~
1.定义一个工具类
public class JsonMapper {
private static ObjectMapper mapper;
private static JsonMapper _instance = new JsonMapper();
private JsonMapper() {
mapper = getMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
// 允许出现特殊字符和转义符
mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
// 允许出现单引号
mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
}
/**
* 取出Mapper做进一步的设置或使用其他序列化API.
*/
public static ObjectMapper getMapper() {
if (mapper == null) {
mapper = new ObjectMapper();
}
return mapper;
}
/**
* 获取实例
*
* @return
*/
public static JsonMapper getInstance() {
return _instance;
}
/**
* 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合.
*
*/
public <T> T fromJson(String jsonString, Class<T> clazz) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return mapper.readValue(jsonString, clazz);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 如果对象为Null, 返回"null". 如果集合为空集合, 返回"[]".
*/
public String toJson(Object object) {
try {
return mapper.writeValueAsString(object);
} catch (IOException e) {
logger.warn("write to json string error:" + object, e);
return null;
}
}
}
注意的是Object是使用JACKSON库
2.json字符串与JAVA对象相互转换
a.将json字符串转换成java对象
Object object = JsonMapper.getInstance().fromJson(result, Object.class);
Object是你要转换的类,这里我用Object代替一下
b.将java对象转换成json字符串
String json = JsonMapper.getInstance().toJson(dto);
dto就是你想转换的对象,dto可以是对象类也可以是集合