使用Android Studio 3.0时如何存储json数据?

时间:2017-11-16 02:20:56

标签: json kotlin android-studio-3.0

在我的Android应用程序中,我设计了以下json数据构造,将来会读取,添加,更新和删除节点的json数据。

我想我应该存储json数据,如何保存json数据?我是否必须将其保存为文件夹\ assets?

下的文本文件

还有,还有一种处理json数据的简单方法吗?我需要使用Gson库吗?

{
   "Setting": [

      {
        "id": "34345",
        "Bluetooth": { "Status": "ON" },
        "WiFi": { "Name": "MyConnect", "Status": "OFF"  }
      }
      ,

      {
         "id": "16454",
         "Bluetooth": { "Status": "OFF" }
      }

   ]

}

1 个答案:

答案 0 :(得分:2)

与答案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<YourObject>(json, YourObject::class.java)

如果您有大量数据,请查看https://developer.android.com/guide/topics/data/data-storage.html选项