jackson工具类
1 package com.booway.util; 2 3 import java.util.List; 4 5 import com.fasterxml.jackson.core.JsonProcessingException; 6 import com.fasterxml.jackson.databind.JavaType; 7 import com.fasterxml.jackson.databind.JsonNode; 8 import com.fasterxml.jackson.databind.ObjectMapper; 9 10 /** 11 * json工具 12 * @author wzh 13 * 14 */ 15 public class JsonUtils { 16 17 private static final ObjectMapper MAPPER = new ObjectMapper(); 18 19 public static String objectToJson(Object data) { 20 String string = null; 21 try { 22 string = MAPPER.writeValueAsString(data); 23 } catch (JsonProcessingException e) { 24 e.printStackTrace(); 25 } 26 return string; 27 } 28 29 public static <T> T jsonToPojo(String jsonData, Class<T> beanType) { 30 T t = null; 31 try { 32 t = MAPPER.readValue(jsonData, beanType); 33 return t; 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } 37 return t; 38 } 39 40 public static <T>List<T> jsonToList(String jsonData, Class<?> target, Class<T> beanType) { 41 42 JavaType javaType = MAPPER.getTypeFactory().constructParametricType(target, beanType); 43 List<T> list = null; 44 try { 45 list = MAPPER.readValue(jsonData, javaType); 46 } catch (Exception e) { 47 e.printStackTrace(); 48 } 49 return list; 50 } 51 52 private static BwjsResult build(boolean successful, String message, Object data) { 53 54 return new BwjsResult(successful, message, data); 55 } 56 57 public static BwjsResult formatToPojo(String jsonData, Class<?> clazz) { 58 try { 59 if (clazz == null) { 60 return MAPPER.readValue(jsonData, BwjsResult.class); 61 } 62 JsonNode jsonNode = MAPPER.readTree(jsonData); 63 JsonNode data = jsonNode.get("data"); 64 Object obj = null; 65 if (clazz != null) { 66 if (data.isObject()) { 67 obj = MAPPER.readValue(data.traverse(), clazz); 68 } else if (data.isTextual()) { 69 obj = MAPPER.readValue(data.asText(), clazz); 70 } 71 } 72 return build(jsonNode.get("successful").booleanValue(), jsonNode.get("msg").asText(), obj); 73 } catch (Exception e) { 74 return null; 75 } 76 } 77 78 public static BwjsResult format(String json) { 79 try { 80 return MAPPER.readValue(json, BwjsResult.class); 81 } catch (Exception e) { 82 e.printStackTrace(); 83 } 84 return null; 85 } 86 87 public static BwjsResult formatToList(String jsonData, Class<?> clazz) { 88 try { 89 JsonNode jsonNode = MAPPER.readTree(jsonData); 90 JsonNode data = jsonNode.get("data"); 91 Object obj = null; 92 if (data.isArray() && data.size() > 0) { 93 obj = MAPPER.readValue(data.traverse(), 94 MAPPER.getTypeFactory().constructCollectionType(List.class, clazz)); 95 } 96 return build(jsonNode.get("successful").booleanValue(), jsonNode.get("msg").asText(), obj); 97 } catch (Exception e) { 98 return null; 99 } 100 } 101 }