JsonUtil java常用工具类
依赖:
<dependency>
<groupId></groupId>
<artifactId>gson</artifactId>
</dependency>
代码:
import .*;
import ;
import ;
import ;
import ;
import ;
/**
*
* @author bl
*
*/
public class JSONUtil {
private static Gson gson = null;
static {
// todo yyyy-MM-dd HH:mm:ss
gson = new Gson();
}
public static synchronized Gson newInstance() {
if (gson == null) {
gson = new Gson();
}
return gson;
}
public static String toJson(Object obj) {
return (obj);
}
public static <T> T toBean(String json, Class<T> clz) {
return (json, clz);
}
public static <T> Map<String, T> toMap(String json, Class<T> clz) {
Map<String, JsonObject> map = (json, new TypeToken<Map<String, JsonObject>>() {
}.getType());
Map<String, T> result = new HashMap<>();
for (String key : ()) {
(key, ((key), clz));
}
return result;
}
public static Map<String, Object> toMap(String json) {
Map<String, Object> map = (json, new TypeToken<Map<String, Object>>() {
}.getType());
return map;
}
public static <T> List<T> toList(String json, Class<T> clz) {
JsonArray array = new JsonParser().parse(json).getAsJsonArray();
List<T> list = new ArrayList<>();
for (final JsonElement elem : array) {
((elem, clz));
}
return list;
}
}