gradle仓库地址:
// https://mvnrepository.com/artifact/com.google.code.gson/gson
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'
package utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.$Gson$Types;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* JSON对象映射解析工具类
*
* @author audaque
*
*/
public class GsonUtils {
public static <T> T getObject(String jsonString, Class<T> cls) {
T t = null;
try {
GsonBuilder builder = new GsonBuilder();
DateDeserializer deserializer = new DateDeserializer();
builder.registerTypeAdapter(Date.class, deserializer);
Gson gson = builder.create();
t = gson.fromJson(jsonString, cls);
} catch (Exception e) {
Logger.getLogger(GsonUtils.class.getName()).log(Level.SEVERE, null, e);
}
return t;
}
public static <T> List<T> getObjects(String jsonString, Class<T> cls) {
try {
GsonBuilder builder = new GsonBuilder();
DateDeserializer deserializer = new DateDeserializer();
builder.registerTypeAdapter(Date.class, deserializer);
Gson gson = builder.create();
Type tp = $Gson$Types.newParameterizedTypeWithOwner(null, (Type) List.class, cls);
return gson.fromJson(jsonString, tp);
} catch (Exception e) {
Logger.getLogger(GsonUtils.class.getName()).log(Level.SEVERE, null, e);
}
return null;
}
public static List<String> getList(String jsonString) {
List<String> list = new ArrayList<String>();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken<List<String>>() {
}.getType());
} catch (Exception e) {
Logger.getLogger(GsonUtils.class.getName()).log(Level.SEVERE, null, e);
}
return list;
}
public static List<Map<String, Object>> listKeyMap(String jsonString) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString,
new TypeToken<List<Map<String, Object>>>() {
}.getType());
} catch (Exception e) {
Logger.getLogger(GsonUtils.class.getName()).log(Level.SEVERE, null, e);
}
return list;
}
public static String getJsonString(Object obj) {
String json = null;
try {
// Gson gson = new Gson();
GsonBuilder builder = new GsonBuilder();
builder.disableHtmlEscaping();
DateSerializer serializer = new DateSerializer();
builder.registerTypeAdapter(Date.class, serializer);
Gson gson = builder.create();
json = gson.toJson(obj);
} catch (Exception e) {
Logger.getLogger(GsonUtils.class.getName()).log(Level.SEVERE, null, e);
}
return json;
}
}