1 package com.myhexin.core.mapping; 2 3 import java.io.IOException; 4 import java.util.List; 5 6 import org.codehaus.jackson.JsonGenerationException; 7 import org.codehaus.jackson.JsonParseException; 8 import org.codehaus.jackson.map.JsonMappingException; 9 import org.codehaus.jackson.map.ObjectMapper;10 import org.codehaus.jackson.type.TypeReference;11 import org.slf4j.Logger;12 import org.slf4j.LoggerFactory;13 14 /**15 * 一些json与对象转换的工具集合类16 * 17 * 18 */19 public class JsonUtils {20 21 private static Logger logger = LoggerFactory.getLogger(JsonUtils.class);22 23 private static final ObjectMapper objectMapper = new ObjectMapper();24 25 private JsonUtils(){}26 public static ObjectMapper getInstance() { 27 return objectMapper; 28 } 29 30 /**31 * 使用Jackson 数据绑定 将对象转换为 json字符串32 * 33 * 还可以 直接使用 JsonUtils.getInstance().writeValueAsString(Object obj)方式 34 * @param obj35 * @return36 */37 public static String toJsonString(Object obj) {38 try {39 return objectMapper.writeValueAsString(obj);40 } catch (JsonGenerationException e) {41 logger.error("转换为json字符串失败" + e.toString());42 } catch (JsonMappingException e) {43 logger.error("转换为json字符串失败" + e.toString());44 } catch (IOException e) {45 logger.error("转换为json字符串失败" + e.toString());46 }47 return null;48 }49 50 /**51 * json字符串转化为 JavaBean52 * 53 * 还可以直接JsonUtils.getInstance().readValue(String content,Class valueType)用这种方式54 * @param 55 * @param content56 * @param valueType57 * @return58 */59 public static T toJavaBean(String content, Class valueType) {60 try {61 return objectMapper.readValue(content, valueType);62 } catch (JsonParseException e) {63 logger.error("json字符串转化为 javabean失败" + e.toString());64 } catch (JsonMappingException e) {65 logger.error("json字符串转化为 javabean失败" + e.toString());66 } catch (IOException e) {67 logger.error("json字符串转化为 javabean失败" + e.toString());68 }69 return null;70 }71 72 /**73 * json字符串转化为list74 * 75 * 还可以 直接使用 JsonUtils.getInstance().readValue(String content, new TypeReference >(){})方式76 * @param 77 * @param content78 * @param valueType79 * @return80 * @throws IOException 81 */82 public static List toJavaBeanList(String content, TypeReference > typeReference) throws IOException {83 try {84 return objectMapper.readValue(content, typeReference);85 } catch (JsonParseException e) {86 logger.error("json字符串转化为 list失败,原因:" + e.toString());87 throw new RuntimeException("json字符串转化为 list失败");88 } catch (JsonMappingException e) {89 logger.error("json字符串转化为 list失败,原因" + e.toString());90 throw new JsonMappingException("json字符串转化为 list失败");91 } catch (IOException e) {92 logger.error("json字符串转化为 list失败,原因" + e.toString());93 throw new IOException("json字符串转化为 list失败");94 }95 }96 97 }