如何在 SharedPreferences 中保存 JSON 数组? [英] How to save JSON Array in SharedPreferences?
本文介绍了如何在 SharedPreferences 中保存 JSON 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Android 新手.我想在共享首选项中保存 JSON 数组.
I am new in Android. I want to save JSON Array in Shared Preferences.
这是我的 Java 代码:
while (managedCursor.moveToNext())
{
JSONObject jsonObject = new JSONObject();
try
{
jsonObject.put("number", number);
jsonObject.put("type", type);
jsonObject.put("fDate", fDate);
jsonObject.put("duration", duration);
}
catch (Exception e)
{
e.printStackTrace();
}
jsonArray.put(jsonObject);
}
managedCursor.close();
Log.d("array", jsonArray.toString());
推荐答案
首先,我会使用 Gson
将 json 转换为/从 Java 对象,然后可以使用类似以下内容存储在 <代码>共享首选项代码>.
Firstly, I'd use Gson
for converting json to/from Java objects,then can use something like following to store in SharedPreferences
.
public void storeMyData(MyPojo myPojo) {
preferences.edit().putString(SOME_SHARED_PREF_KEY, gson.toJson(myPojo)).commit();
}
将json转换为字符串并保存到sharedpreference
convert json to string and save to sharedpreference
preferences.edit().putString(SOME_SHARED_PREF_KEY,jsonobject.toString()).commit();
从 sharedPreference 读取转换回 json
on reading from sharedPreference convert back to json by
String string = preferences.getString(SOME_SHARED_PREF_KEY, null);
JsonObject jsonObject = new JsonObject(string);
这篇关于如何在 SharedPreferences 中保存 JSON 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文