一、让我们从引入依赖开始
//将这两行代码添加到以上位置,其他的一般不用管
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.tencent:mmkv:1.2.13'
二、一个简单实现
... //Other import
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mmkv.MMKV;
public class MyApplication extends Application {
//这里的Your_Type和Your_List你可以改成自己需要的类型和名字
private ArrayList Your_List;
@Override
public void onCreate() {
super.onCreate();
//使MMKV库在当前环境初始化;
MMKV.initialize(this);
//它一般会被添加到onCreate()方法里;
//因为要确保:用之前已经调用此方法
}
public void saveList_to_Json(){//保存数据的方法
//创建Gson实例
Gson gson = new Gson();
// 获取 MMKV 实例
MMKV kv = MMKV.defaultMMKV();
// 将 List 转换为 JSON 字符串
String jsonList = gson.toJson(Your_List);
// 保存 JSON 字符串,并设置一个Key
kv.encode("Your_Key", jsonList);
// 这个方法的第一个参数是 要保存的数据数据(Value)的名字(Key)
// 自己起名就行,以后就可以用这个名字(Key),来找到对应的数据了,像字典一样
}//void saveList_to_Json
public void readJson_toList(){//读取数据的方法
Gson gson = new Gson();
MMKV kv = MMKV.defaultMMKV();
// 从 MMKV 中读取 Key为"Your_Key"的 JSON 字符串
String jsonList = kv.decodeString("Your_Key");
if(jsonList!=null){
//把Json转为对应类型的数据,并保存到变量中
Your_List = gson.fromJson(jsonList, new TypeToken>(){}.getType());
//new TypeToken>(){} 实例化一个TypeToken,并保存了ArrayList类型
//getType() 获取类型,jsonList将按照之前类型(也就是这个:ArrayList)进行解析
}
}//void readJson_toList
}//class MyApplication
参与评论
手机查看
返回顶部