版权声明:本文为博主原创文章,未经博主允许不得复制发布,转载没问题的!盗内容你丫就是我儿子。 https://blog.csdn.net/u010785811/article/details/76889524
这是Json和Bean的转换
废话不说上代码
/**
* Use jacksonMapper Convert JSON to Bean
*
* @param obj
* Source Object
* @return JSON String
* @throws CommonException
*/
public static String bean2JSON(Object obj) throws CommonException {
String errorMessage = "The operation of bean2Json has been error!";
ObjectMapper objectMapper = null;
StringBuffer strBuffer = new StringBuffer("");
objectMapper = new ObjectMapper();
try {
strBuffer.append(objectMapper.writeValueAsString(obj));
} catch (JsonGenerationException e) {
throw new CommonException(errorMessage, e);
} catch (JsonMappingException e) {
throw new CommonException(errorMessage, e);
} catch (IOException e) {
throw new CommonException(errorMessage, e);
}
return strBuffer.toString();
}
/**
* Use jacksonMapper Convert JSON to Bean
*
* @param json
* JSON String
* @param clz
* Target Class Object
* @return Target Object
* @throws CommonException
*/
public static <T> T json2Bean(String json, Class<T> clz) throws CommonException {
String errorMessage = "The operation of json2Bean has been error!";
try {
ObjectMapper objectMapper = new ObjectMapper();
return (T) objectMapper.readValue(json, clz);
} catch (JsonParseException e) {
throw new CommonException(errorMessage, e);
} catch (JsonMappingException e) {
throw new CommonException(errorMessage, e);
} catch (IOException e) {
throw new CommonException(errorMessage, e);
}
}