1. 程式人生 > >json資料轉化工具類示例

json資料轉化工具類示例

import com.dtyunxi.lang.BusinessRuntimeException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public final class JacksonUtil {


public static ObjectMapper objectMapper = new ObjectMapper();


/**
* 使用泛型方法,把json字串轉換為相應的JavaBean物件。
* (1)轉換為普通JavaBean:readValue(json,Student.class)
* (2)轉換為List,如List<Student>,將第二個引數傳遞為Student
* [].class.然後使用Arrays.asList();方法把得到的陣列轉換為特定型別的List

* @param jsonStr
* @param valueType
* @return
*/
public static <T> T readValue(String jsonStr, Class<T> valueType) {
try {
return objectMapper.readValue(jsonStr, valueType);
} catch (Exception e) {
throw new BusinessRuntimeException("JacksonUtil.readValue(String,Class<T>)執行異常", e);
}
}


/**
* json陣列轉List

* @param jsonStr
* @param valueTypeRef
* @return
*/
public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef) {  //eg:readValue(str,new TypeReference<List<Student>>(){})  呼叫
try {
return objectMapper.readValue(jsonStr, valueTypeRef);
} catch (Exception e) {
throw new BusinessRuntimeException("JacksonUtil.readValue(String,TypeReference<T>)執行異常", e);
}
}



/**
* 把JavaBean轉換為json字串

* @param object
* @return
*/
public static String toJson(Object object) {
try {
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
throw new BusinessRuntimeException("JacksonUtil.toJSon執行異常", e);
}
}


}