Json 工具类
一、使用方法
(1/4)普通对象转Json
DodoFile file = new DodoFile();
file.setFileName("test.file");
String s = JacksonUtil.toJackson(file);
System.err.println(s);
(2/4)Json转普通对象
DodoFile file = new DodoFile();
file.setFileName("test.file");
String s = JacksonUtil.toJackson(file);
System.err.println(s);
DodoFile file2 = JacksonUtil.toObject(s, DodoFile.class);
System.err.println(file2);
(3/4)集合对象转Json
Map<String, DodoFile> files = new HashMap<String, DodoFile>();
DodoFile file = new DodoFile();
file.setFileName("test.file");
files.put("key1", file);
String s = JacksonUtil.toJackson(files);
System.err.println(s);
(4/4)Json转集合对象
Map<String, DodoFile> files = new HashMap<String, DodoFile>();
DodoFile file = new DodoFile();
file.setFileName("test.file");
files.put("key1", file);
String s = JacksonUtil.toJackson(files);
System.err.println(s);
Map<String, DodoFile> files2 = JacksonUtil.toObject(s, new TypeReference<Map<String, DodoFile>>() {});
System.err.println(files2);
Map<String, DodoFile> files3 = JacksonUtil.toCollectionObject(s, Map.class, String.class, DodoFile.class);
System.err.println(files3);
二、注释说明
public class JacksonUtil {
private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static String toJackson(Object object) throws JsonProcessingException {
return object == null ? null : OBJECT_MAPPER.writeValueAsString(object);
}
public static <T> T toObject(String jsonStr, Class<T> clazz) throws IOException {
if (StringUtils.isBlank(jsonStr)) {
return null;
}
return OBJECT_MAPPER.readValue(jsonStr, clazz);
}
public static <T> T toObject(String jsonStr, TypeReference<?> typeReference) throws IOException,
JsonParseException, JsonMappingException {
if (StringUtils.isBlank(jsonStr)) {
return null;
}
return OBJECT_MAPPER.readValue(jsonStr, typeReference);
}
public static <T> T toCollectionObject(String jsonStr, Class<?> collectionClass, Class<?>... elementClasses)
throws IOException, JsonParseException, JsonMappingException {
if (StringUtils.isBlank(jsonStr)) {
return null;
}
return OBJECT_MAPPER.readValue(jsonStr, getCollectionType(collectionClass, elementClasses));
}
private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
return OBJECT_MAPPER.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
}