1. 程式人生 > 實用技巧 >java物件與json格式相互轉換的工具類

java物件與json格式相互轉換的工具類

1. 內容

 1 public class PfJacksonUtils {
 2     private PfJacksonUtils() {
 3 
 4     }
 5 
 6     public static String beanToJson(Object obj) throws JsonProcessingException {
 7         ObjectMapper objectMapper = new ObjectMapper();
 8         return objectMapper.writeValueAsString(obj);
 9     }
10
11 public static <T> T jsonToBean(String json, Class<T> cls) 12 throws JsonParseException, JsonMappingException, IOException { 13 ObjectMapper objectMapper = new ObjectMapper(); 14 if (json == null) { 15 return objectMapper.readValue("{}", cls);
16 } 17 return objectMapper.readValue(json, cls); 18 } 19 20 public static String mapToJson(Map<String, String> map) throws JsonProcessingException { 21 ObjectMapper mapper = new ObjectMapper(); 22 return mapper.writeValueAsString(map); 23 } 24 25 public
static <T> T jsonToBeanByMatchAttribute(String json, Class<T> cls) 26 throws JsonParseException, JsonMappingException, IOException { 27 if (StringUtils.isEmpty(json)) { 28 return null; 29 } 30 ObjectMapper objectMapper = new ObjectMapper(); 31 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 32 return objectMapper.readValue(json, cls); 33 } 34 }

2. 用法

1 String json = PfJacksonUtils.beanToJson(object);
2 PmDataInfo pmDataInfo = PfJacksonUtils.jsonToBeanByMatchAttribute(json, PmDataInfo.class);