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()); } } } </pre><br />
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!