Skip to content
Advertisement

Why is my LinkedHashMap being incorrectly converted to JSON and saved in SharedPreferences?

I’m trying to save an object in SharedPreferences but first converting the object to JSON as shown below. However, the object is being both incorrectly converted and saved.

    private void saveSchedule() {
        String jsonString = new Gson().toJson(schedule);
        SharedPreferences sharedPreferences = getSharedPreferences("Schedule", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("schedule", jsonString);
        editor.apply();
    }

The JSON looks like this:

E/ {"com.example.****.****.HobbyApp@a64232":["Hobby1","Hobby2","Hobby3"]}

This makes it impossible to save and retrieve the schedule.

Why is the name of the schedule file address being converted into JSON and saved instead of the values? Please help, thank you!

Advertisement

Answer

JSON only supports strings as JSON object property names. Gson therefore by default calls the toString() method to convert non-String Map keys to strings.

If instances of your Hobby class can easily be represented as string, you could override its toString() method. For deserialization you will however likely have to register a custom TypeAdapter.

Otherwise you can uses GsonBuilder.enableComplexMapKeySerialization() which will serialize your Map as JSON array.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement