Android使用Gson和SharedPreferences存储对象

来源:互联网 发布:mcmc算法 编辑:程序博客网 时间:2024/05/16 01:07

Android存储文件通常可以用SharedPreferences、SQLite、Content Provider和File,但是SharedPreferences只支持简单的key-value,

通常,如果要存储一个对象,可以先把它序列化,然后用输入输出流存进file文件


另一个我比较喜欢的方式是:

写:先把一个对象用gson解析成json字符串(使用gson的toJson函数),然后当成一个value写进SharedPreferences里面

读:读取出来的时候就再次用gson把json解析成对象(使用gson的fromJson函数)

参考:

Android中的JSON详细总结

怎样使用Gson 解析 (deserialize) json字符串

Gson简要使用笔记



代码实现:





参考:

Json转换利器Gson之实例一-简单对象转化和带泛型的List转化 (http://blog.csdn.net/lk_blog/article/details/7685169)
Json转换利器Gson之实例二-Gson注解和GsonBuilder (http://blog.csdn.net/lk_blog/article/details/7685190)
Json转换利器Gson之实例三-Map处理(上) (http://blog.csdn.net/lk_blog/article/details/7685210)
Json转换利器Gson之实例四-Map处理(下) (http://blog.csdn.net/lk_blog/article/details/7685224)
Json转换利器Gson之实例五-实际开发中的特殊需求处理 (http://blog.csdn.net/lk_blog/article/details/7685237)
Json转换利器Gson之实例六-注册TypeAdapter及处理Enum类型 (http://blog.csdn.net/lk_blog/article/details/7685347)




新的SharedPreference 操作类, 简化了使用的参数   http://my.oschina.net/sfshine/blog/219384





0 0
原创粉丝点击