package com.zsh.commons.utils;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* JSON工具,用于与对象的互相转换
*/
public abstract class JsonUtil {
private static final ObjectMapper mapper;
static {
mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
mapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
}
/**
* 将json字符串转换成对象
*/
public static Object parse(String json, Class<?> clazz) {
try {
return mapper.readValue(json, clazz);
} catch (IOException e) {
throw new IllegalArgumentException("无法解析JSON对象", e);
}
}
/**
* 将java对象格式化为字符串
*/
public static String format(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (IOException e) {
throw new IllegalArgumentException("格式化对象为JSON格式出错", e);
}
}
/**
* 将json字符串转换成JsonNode对象
*/
public static JsonNode parse(String json) {
try {
return mapper.readTree(json);
} catch (IOException e) {
throw new IllegalArgumentException("格式化对象为JSON格式出错", e);
}
}
/**
* 将json字符串转换成map
*/
public static Map<String, Object> parseMap(String json) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructParametricType(HashMap.class, String.class, Object.class));
} catch (IOException e) {
throw new IllegalArgumentException("无法解析JSON对象", e);
}
}
/**
* 将json字符串转换成list
*/
public static List<?> parseList(String json, Class<?> clazz) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructParametricType(List.class, clazz));
} catch (IOException e) {
throw new IllegalArgumentException("无法解析JSON对象", e);
}
}
}
JSON工具,用于与对象的互相转换
最新推荐文章于 2021-02-03 23:04:24 发布