pwittchen / prefser

Wrapper for Android SharedPreferences with object serialization and RxJava Observables
Apache License 2.0
229 stars 26 forks source link

Create a fromJson method that accepts a Type #44

Closed tsuharesu closed 9 years ago

tsuharesu commented 9 years ago

Gson can convert from a TypeToken, and sometimes that is desirable. One thing that I'm having trouble is that I need a List and Gson is returning me a List. I can't pass a List.class because it does not exists, and I can't pass a Type too because the interface don't have this method.

The way I'm trying to do and the return value is wrong:

List<Account> accounts = prefser.get(Constants.PreferencesKeys.ACCOUNTS, List.class, new ArrayList<>())
tsuharesu commented 9 years ago

I'm getting the list as an Array for now:

Account[] accounts = prefser.get(Constants.PreferencesKeys.ACCOUNTS, Account[].class, new Account[]{});
pwittchen commented 9 years ago

Hello. I know about this issue. It was listed in a caveats section in README file. Currently, you can use an array instead of list. You can browse examples to check usage with arrays, but I see you've already know it. I'll try to improve this solution in order to provide the possibility to serialize and deserialize lists of generic types with Gson. I need to read more about Gson and perform some tests to make it happen. Moreover, you can use different JsonConverter implementation than Gson and provide it during creating new instance of prefser.

tsuharesu commented 9 years ago

Yeah, the problem with the JsonConverter is that the method still needs a Class. I didn't saw caveats before, thanks for the explanation :)

pwittchen commented 9 years ago

It's done in PR #49 thanks to @ypresto.

I still need to update documentation in README.md, but now you can check some examples of usage in unit tests located in PrefserTest class. I'm going to add more unit tests for Observables from Lists soon. This feature will be available in the next release.