当我使用Android Studio 3.0时如何存储json数据?
在我的Android应用程序中,我设计了下面的json数据构造,json数据将在未来被读取,添加,更新和删除节点。
我想我应该存储JSON数据,我怎么能坚持JSON数据? 我必须将其保存为文件夹\资产下的文本文件吗?
还有,有一个简单的方法来处理JSON数据? 我需要使用Gson库吗?
{ "Setting": [ { "id": "34345", "Bluetooth": { "Status": "ON" }, "WiFi": { "Name": "MyConnect", "Status": "OFF" } } , { "id": "16454", "Bluetooth": { "Status": "OFF" } } ] }
比较答案https://stackoverflow.com/a/18463758/4265739
最简单的方法是使用SharedPreferences
和Gson。
在Gradle文件中添加GSON依赖项:
compile 'com.google.code.gson:gson:2.8.0'
为Kotlin调整的代码是存储:
val prefsEditor = PreferenceManager.getDefaultSharedPreferences(this).edit() val json = Gson().toJson(yourObject) prefsEditor.putString("yourObject", json) prefsEditor.commit()
检索:
val json: String = sp.getString("yourObject", "") val yourObject = Gson().fromJson(json, YourObject::class.java)
如果您有大量数据, 请参阅https://developer.android.com/guide/topics/data/data-storage.html
- AAR / JAR不会使用Android Studio 3.0 Canary 7生成
- 为什么Android Studio 3测试版有Build APK(s)选项而不是Build APK?
- Android Studio + Spek集成
- 为什么在AndroidStudio 3.0中运行kotlin测试非常慢?
- 不寻常的崩溃只有在一些设备 – 异步调用kotlin协同程序
- kotlin文件如何在android studio 3.0 Canary 4上运行?
- 为什么我不能指定我的Kotlin文件在Android Studio中的位置?
- Android 3.0 Canary生成错误:不支持major.minor版本52.0
- 两个并发字符串替换为kotlin字符串