如何从 android 中的共享首选项存储和获取 JSON 对象
How to store and get JSON Object from Shared Preferences in android
将 JSON 对象存储到字符串是可能的。但是有什么方法可以像在共享首选项中那样存储 JSON 对象并进行检索吗?
JSONObject data_obj = new JSONObject();
JSONArray arr_obj = new JSONArray();
JSONObject main_obj = new JSONObject();
data_obj.put("id", "1");
data_obj.put("name", "Loin");
arr_obj.put(data_obj);
main_obj.put("user_review", arr_obj);
main_obj 将如何存储在共享首选项中?
JSONObject 最终是一个key/value 对字符串,所以使用toString()
将其转换为字符串并保存!
您可以将 JsonObject 转换为 String 并将该字符串放在共享首选项中,然后可以执行反向操作以获取 JsonObject。
A JSONObject is an unordered collection of name/value pairs. Its
external form is a string wrapped in curly braces with colons between
the names and values, and commas between the values and names.
例如,
String myString = new JSONObject().put("JSON", "Hello, World!").toString();
print(myString) it produces the string {"JSON": "Hello, World"}.
对于反向器你可以做
JSONObject myJSON = new JSONObject(myString);
对于 SharedPreference,您可以 refer
将 JSON 对象存储到字符串是可能的。但是有什么方法可以像在共享首选项中那样存储 JSON 对象并进行检索吗?
JSONObject data_obj = new JSONObject();
JSONArray arr_obj = new JSONArray();
JSONObject main_obj = new JSONObject();
data_obj.put("id", "1");
data_obj.put("name", "Loin");
arr_obj.put(data_obj);
main_obj.put("user_review", arr_obj);
main_obj 将如何存储在共享首选项中?
JSONObject 最终是一个key/value 对字符串,所以使用toString()
将其转换为字符串并保存!
您可以将 JsonObject 转换为 String 并将该字符串放在共享首选项中,然后可以执行反向操作以获取 JsonObject。
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.
例如,
String myString = new JSONObject().put("JSON", "Hello, World!").toString();
print(myString) it produces the string {"JSON": "Hello, World"}.
对于反向器你可以做 JSONObject myJSON = new JSONObject(myString);
对于 SharedPreference,您可以 refer