1.String類型的Json數據轉換成Map格式:
final static ObjectMapper mapper = new ObjectMapper();
public static Map<String, Object> convertPojoToMap(Object pojo) {
Map<String, Object> map = mapper.convertValue(pojo, Map.class);
return map;
}
2.Json數據轉換成String字符串:
public static String convertPojoToJsonString(Object pojo) throws JsonProcessingException {
return mapper.writeValueAsString(pojo);
}
3.文件中讀取Json數據成Map格式:
public static Map getMapDataFromFile(String fileLocation) throws Exception {
try {
ClassLoader loader = ClassLoader.getSystemClassLoader();
Map result = mapper.readValue(new File(loader.getResource(fileLocation).getPath()), Map.class);
return result;
} catch (Exception e) {
throw new SystemException("Can't returm map object from file [" + fileLocation + "].", e);
}
}
4.不限制格式數據轉換:
public static <T> T generatePojoFromString(String content, Class<T> pojoClass) throws Exception {
T pojo = mapper.readValue(content, pojoClass);
return pojo;
}
上述用到的ObjectMapper來自com.fasterxml.jackson.databind。jackson相關的包需要自行到官網下載: