当我使用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
- 在另一个模块的function模块中找不到Kotlin类
- 如何使用drawLine()绘制线条
- 如果活动写在Kotlin中,Button onClick属性是none
- 如何将一个字符串传递给Kotlin中没有转义符号的variables?
- Gradle 3.0.0(在Android Studio 3.0中)重新排列任务序列(用Kotlin模块编译时)?
- Android Studio 3.0 Canary 2:未找到属性“android:versionCode”
- Kotlingenericstypes,types推断失败
- 无法使用Android Studio 3.0 + DataBinding + Kotlin构建项目
- 使用Android Studio 3.0 beta7版本时,Kotlin注释处理器会导致编译时错误