1

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" }
      }

   ]

}
HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

2

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

leonardkraemer
  • 6,573
  • 1
  • 31
  • 54
  • Thanks! Do I have limitation with number of characters of json when I store json string using SharedPreferences ? such as, the number of characters of json string can't exceed 256. – HelloCW Nov 16 '17 at 06:34
  • As far as I know the limitation is that your data must fit in the heap. So no. Nevertheless I would not go for SharedPreferences if your data exceeds ~1MB. Apps with > 10MB exist though. – leonardkraemer Nov 16 '17 at 10:34