Android: Save map to SharedPreferences?

Slaknation :

I need to save data to SharedPreferences in such a way where I have an object like this:

{
    "days": [
        {
            "exercises": [
                {
                    "name": "Bench Press",
                    "sets": 3,
                    "reps": 8
                },
                {
                    "name": "Skull Crushers",
                    "sets": 3,
                    "reps": 8
                },
                {
                    "name": "Flys",
                    "sets": 3,
                    "reps": 8
                }
            ]
        },
        {
            "exercises": [
                {
                    "name": "Bench Press",
                    "sets": 3,
                    "reps": 8
                },
                {
                    "name": "Skull Crushers",
                    "sets": 3,
                    "reps": 8
                },
                {
                    "name": "Flys",
                    "sets": 3,
                    "reps": 8
                }
            ]
        }
    ]
}

I will need to pull from the object and add to the object. I know that you can't save maps to SharedPreferences. I am starting to think that my best bet is to use ObjectOutputStream but I am not sure if that is the best bet to use internal memory. I guess I am just looking for guidance as to what my best options are.

edit: from what Advice-Dog said, I am thinking my best bet is to use gson. So does that mean that when I want to (for example) add another exercise to the second index of "days" that I will first grab the object from preferences, convert it from gson to an object, then add the exercise, then convert it back to gson, then overwrite the preferences? I am not saying this is bad I just want to know if this is what should be done and if it is advisable.

Advice-Dog :

When saving more complex types in Android, I would suggest using gson. Gson is Google's JSON parsing library, and even if you're not using JSON, you can convert your Objects into a JSON String, and store that easily.

For example, you can convert your list of Objects into a String like this.

val list : List<MyObject>  // ... add items to your list

// Convert to JSON

val string = gson.toJson(list)

// Store it into Shared Preferences
preferences.putString("list", string).apply()

And then you can easily get it back into a list like this.

// Fetch the JSON 

val string = preferences.getString("list", "")

// Convert it back into a List

val list: List<MyObject> = gson.fromJson(string, object : TypeToken<List<MyObject>>() {}.type)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116252&siteId=1