可以在 SharedPreferences 中保存 JSON 数组吗? [英] Is it ok to save a JSON array in SharedPreferences?
问题描述
我有一个需要保存的 JSON 数组.我正在考虑序列化它,但将它保存为 SharedPreferences 中的字符串,然后在需要读取时重建它会更好吗?
I have a JSON Array that I need to save. I was thinking about serializing it, but would it be better to just save it as a string in SharedPreferences and then rebuild it when I need to read it in?
推荐答案
Java 中的 JSON 对象没有实现开箱即用的可序列化.我已经看到其他人扩展了类以允许这样做,但是对于您的情况,我只是建议将 JSON 对象存储为字符串并使用其 toString() 函数.我在这方面取得了成功.
The JSON object in Java does not implement serialaizable out of the box. I have seen others extend the class to allow that but for your situation I would simply recommend storing the JSON object as a string and using its toString() function. I have had success with this.
editor.putString("jsondata", jobj.toString());
并取回它:
String strJson = sharedPref.getString("jsondata","0");//second parameter is necessary ie.,Value to return if this preference does not exist.
if (strJson != null) {
try {
JSONObject response = new JSONObject(strJson);
} catch (JSONException e) {
}
}
http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)
这篇关于可以在 SharedPreferences 中保存 JSON 数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!