Patrick
Patrick

Reputation: 35244

Is it somehow bad practice to store Objects as JSON Strings in SharedPreferences in Android?

As someone who recently discovered the beauty of simplicity of a NoSQL document store (namley CouchDB) I find myself very tempting when needing to persistently store simple Objects or small Arrays to use a Json serializer to store this data as a JSON String in the shared preferences. The advantages I see are:

The disadvantages I see:

Im aware that this approach is only feasible with reasonable small data (but the same applies for SharedPreferences in general, I guess) and the performance hit is negligible if this is only used on a "save config" or similar use cases where writes/reads are sparse.

Im looking for an argument for/against this approach in the depicted scenario or for problems I overlooked or may arise.

Upvotes: 3

Views: 526

Answers (2)

Patrick
Patrick

Reputation: 35244

So after a couple of years here are my findings:

  • Json serialization can be slow when using reflection based serialization and especially if the content is complex and/or long
  • Specific care has to be taken into consideration when using Proguard to not obfuscate the names of the models to serialize.
  • Migration is hard - this is to me the biggest drawback.

So it depends on the use case. Maybe for a cache this might be ok, since it is just performance penalty if the data gets corrupt after an update, on the other side caches should be fast (a memory layer could mitigate that).

If you need a data storage for structred data, use a database or ORM like Google's Room.

Upvotes: 0

jimmy0251
jimmy0251

Reputation: 16463

There's no harm storing small data objects in SharedPreferences. However, one thing you should keep in mind that SharedPreferences does not work properly across multiple processes. So you should avoid using SharedPreferences if you're planning to use them across processes.

Upvotes: 1

Related Questions