There should be many places for gson. Let’s start with a singleton today:
Add dependencies in build.gradle:
implementation 'com.google.code.gson:gson:2.8.5'
Write tools directly:
public class GsonDanli {
private Gson gson;
//构造函数私有化
private GsonDanli(){
gson = new Gson();
}
private static GsonDanli gsonDanlis;
//提供一个公共的、静态的、返回值类型是当前本类的对象
public static GsonDanli getGsonDanli(){
if(gsonDanlis == null){
synchronized (OkHttpUtils.class){
if(gsonDanlis == null) {
gsonDanlis = new GsonDanli();
}
}
}
return gsonDanlis;
}
public Gson getGsons(){
return gson;
}
public <T> T getBean(String s, Class<T> classOfT){
Object object=gson.fromJson(s,classOfT);
return Primitives.wrap(classOfT).cast(object);
}
}