Jackson的Json轉換

public class JacksonJsonUtil {
	private static ObjectMapper mapper;
	
	/**
	 * 獲取ObjectMapper實例
	 * @param createNew 方式:true,新實例;false,存在的mapper實例
	 * @return
	 */
	public static synchronized ObjectMapper getMapperInstance(boolean createNew) {   
        if (createNew) {   
            return new ObjectMapper();   
        } else if (mapper == null) {   
            mapper = new ObjectMapper();   
        }   
        return mapper;   
    } 
	
	/**
	 * 將java對象轉換成json字符串
	 * @param obj 準備轉換的對象
	 * @return json字符串
	 * @throws Exception 
	 */
	public static String beanToJson(Object obj) throws Exception {
		try {
			ObjectMapper objectMapper = getMapperInstance(false);
			String json =objectMapper.writeValueAsString(obj);
			return json;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}		
	}
	
	/**
	 * 將java對象轉換成json字符串
	 * @param obj 準備轉換的對象
	 * @param createNew ObjectMapper實例方式:true,新實例;false,存在的mapper實例
	 * @return json字符串
	 * @throws Exception
	 */
	public static String beanToJson(Object obj,Boolean createNew) throws Exception {
		try {
			ObjectMapper objectMapper = getMapperInstance(createNew);
			String json =objectMapper.writeValueAsString(obj);
			return json;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}		
	}
	
	/**
	 * 將json字符串轉換成java對象
	 * @param json 準備轉換的json字符串
	 * @param cls  準備轉換的類
	 * @return 
	 * @throws Exception 
	 */
	public static Object jsonToBean(String json, Class<?> cls) throws Exception {
		try {
		ObjectMapper objectMapper = getMapperInstance(false);
		Object vo = objectMapper.readValue(json, cls);
		return vo;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}	
	}
	
	/**
	 * 將json字符串轉換成java對象
	 * @param json 準備轉換的json字符串
	 * @param cls  準備轉換的類
	 * @param createNew ObjectMapper實例方式:true,新實例;false,存在的mapper實例
	 * @return
	 * @throws Exception
	 */
	public static Object jsonToBean(String json, Class<?> cls,Boolean createNew) throws Exception {
		try {
		ObjectMapper objectMapper = getMapperInstance(createNew);
		Object vo = objectMapper.readValue(json, cls);
		return vo;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}	
	}
}
相關文章
相關標籤/搜索