简体   繁体   English

以JSON格式的String形式的全局数据保存在SharedPreferences中吗?

[英]Global data as String in JSON format saved in SharedPreferences?

在Android中以JSON格式保存全局数据并在需要时通过SharedPreferences访问它是正确的吗?

I would extract it and save it as a string before using it in shared preferences. 在共享首选项中使用它之前,我将提取它并将其另存为字符串。 It is easier for the app to read the string rather than the JSON formatted response. 应用程序更容易读取字符串,而不是JSON格式的响应。

Therefore do something similar to this: 因此,请执行以下操作:

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();

editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long

editor.commit(); // commit changes

As you can see in the above, there is no predefined sharedpreference for a JSON object or array. 如您在上面所看到的,JSON对象或数组没有预定义的sharedpreference。 Hence it is easier to extract the data from the JSON repsonse to a string and pass on that string in the SharedPreference. 因此,从JSON响应中提取数据到字符串并在SharedPreference中传递该字符串比较容易。

Hope this helps :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM