HelloCW
HelloCW

Reputation: 2325

How to store json data when I use Android Studio 3.0?

In my Android App, I desgin the following json data construction, the json data will be read, added, updated and deleted node in the future.

I think I should store the json data, how can I persist the json data? do I have to save it as text file under the folder \assets ?

And more, is there a simple way to handle json data ? do I need use Gson library?

{
   "Setting": [

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

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

   ]

}

Upvotes: 1

Views: 2792

Answers (1)

leonardkraemer
leonardkraemer

Reputation: 6813

Compare to the answer https://stackoverflow.com/a/18463758/4265739

The easiest way is to use SharedPreferences and Gson.

add GSON dependency in Gradle file:

compile 'com.google.code.gson:gson:2.8.0'

The code adjusted for Kotlin is to store:

val prefsEditor = PreferenceManager.getDefaultSharedPreferences(this).edit()
val json = Gson().toJson(yourObject)
prefsEditor.putString("yourObject", json)
prefsEditor.commit()

to retrieve:

 val json: String = sp.getString("yourObject", "")
 val yourObject = Gson().fromJson<YourObject>(json, YourObject::class.java)

If you have lots of data look at https://developer.android.com/guide/topics/data/data-storage.html for your options

Upvotes: 3

Related Questions