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相关的包需要自行到官网下载: