zoukankan      html  css  js  c++  java
  • SharePrecences--(json+sharePrecences)存list 或对象

     

    利用Gson和SharePreference存储结构化数据

    具体的步骤

    这个假设有三个User对象生成一个ArrayList<User>:

    复制代码
    User user1 = new User("jack", "123456789", "http://www.hello.com/1.png");
    User user2 = new User("tom", "45467956456", "http://www.hello.com/2.png");
    User user3 = new User("lily", "65465897faf", "http://www.hello.com/3.png");
    ArrayList<User> users = new ArrayList<>();
    users.add(user1);
    users.add(user2);
    users.add(user3);
    复制代码

    利用Gson转化ArrayList<User>成Json Array数据:

    Gson gson = new Gson();
    String jsonStr = gson.toJson(users);
    SPUtils.put(mContext, "USERS_KEY", jsonStr);

    这里的jsonStr内容是:

    [{"access_token":"123456789","profile_pic":"http://www.hello.com/1.png","username":"jack"},{"access_token":"45467956456","profile_pic":"http://www.hello.com/2.png","username":"tom"},{"access_token":"65465897faf","profile_pic":"http://www.hello.com/3.png","username":"lily"}]

    这个时候看下sharepreference的xml文件里面有啥:

    复制代码
    <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
    <map>
    <string name="USERS_KEY">[{&quot;access_token&quot;:&quot;123456789&quot;,&quot;profile_pic&quot;:&quot;http://www.hello.com/1.png&quot;,&quot;username&quot;:&quot;jack&quot;},{&quot;access_token&quot;:&quot;45467956456&quot;,&quot;profile_pic&quot;:&quot;http://www.hello.com/2.png&quot;,&quot;username&quot;:&quot;tom&quot;},{&quot;access_token&quot;:&quot;65465897faf&quot;,&quot;profile_pic&quot;:&quot;http://www.hello.com/3.png&quot;,&quot;username&quot;:&quot;lily&quot;}]</string>
    </map>
    复制代码

    发现String数据已经存储到了sharepreference中。那么该如何解析出来成bean对象呢?比如后面需要查jack这个人的对应的profile_pic:

    复制代码
    String str = (String) SPUtils.get(mContext, "USERS_KEY", "");
    users = gson.fromJson(str, new TypeToken<List<User>>() {}.getType());
    for (User user : users) {
        if (user.getUsername().equals("jack")) {
            L.d(user.getProfile_pic());
        }
    }
    复制代码

    在logcat中可以看到成功的打印出了Jack的profile_pic:

    如果需要存储的数据比较多,可以将每个Bean对象抽取出一个key(比如username)形成一个key的ArrayList,同时将这个key的ArrayList存储到SharePreferecene,方便后续取出bean对象。

     

    方法23:存对象 (sharedPreferences+base64)

    注意:
    (1)这里的object必须implement Serializable这个接口。
    (2)本质上这里使用的是String来存储对象,只是先将对象序列化为String了。

    /**
    * 将对象进行base64编码后保存到SharePref中
    * @param key
    * @param object
    */
    public static void saveObj(Context context, String key, Object object) {
    if (sp == null)
    sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = null;
    try {
    oos = new ObjectOutputStream(baos);
    oos.writeObject(object);
    // 将对象的转为base64码
    String objBase64 = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
    sp.edit().putString(key, objBase64).commit();
    oos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    /**
    * 将SharePref中经过base64编码的对象读取出来
    * @param key
    * @param defValue
    */
    public static Object getObj(Context context, String key) {
    if (sp == null)
    sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
    String objBase64 = sp.getString(key, null);
    if (TextUtils.isEmpty(objBase64))
    return null;
    // 对Base64格式的字符串进行解码
    byte[] base64Bytes = Base64.decode(objBase64.getBytes(), Base64.DEFAULT);
    ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
    ObjectInputStream ois;
    Object obj = null;
    try {
    ois = new ObjectInputStream(bais);
    obj = (Object) ois.readObject();
    ois.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return obj;
    }

     

    方法22:保存List(Map(String, String)),(SharedPreferences+JsonArray )

    原因:
    SharedPreferences没有保存数组的方法,但是有时候为了保存一个数组而进行序列化,或者 动用sqlite都是有点杀猪焉用牛刀的感觉,所以就自己动手改进一下吧。

    解决方案:方式是先转换成JSON,然后保存字符串,取出的时候再讲JSON转换成数组就好了。


    public void saveInfo(Context context, String key, List<Map<String, String>> datas) {
    JSONArray mJsonArray = new JSONArray();
    for (int i = 0; i < datas.size(); i++) {
    Map<String, String> itemMap = datas.get(i);
    Iterator<Entry<String, String>> iterator = itemMap.entrySet().iterator();
    JSONObject object = new JSONObject();

    while (iterator.hasNext()) {
    Entry<String, String> entry = iterator.next();
    try {
    object.put(entry.getKey(), entry.getValue());
    } catch (JSONException e) {

    }
    }
    mJsonArray.put(object);
    }

    SharedPreferences sp = context.getSharedPreferences("finals", Context.MODE_PRIVATE);
    Editor editor = sp.edit();
    editor.putString(key, mJsonArray.toString());
    editor.commit();
    }

    public List<Map<String, String>> getInfo(Context context, String key) {
    List<Map<String, String>> datas = new ArrayList<Map<String, String>>();
    SharedPreferences sp = context.getSharedPreferences("finals", Context.MODE_PRIVATE);
    String result = sp.getString(key, "");
    try {
    JSONArray array = new JSONArray(result);
    for (int i = 0; i < array.length(); i++) {
    JSONObject itemObject = array.getJSONObject(i);
    Map<String, String> itemMap = new HashMap<String, String>();
    JSONArray names = itemObject.names();
    if (names != null) {
    for (int j = 0; j < names.length(); j++) {
    String name = names.getString(j);
    String value = itemObject.getString(name);
    itemMap.put(name, value);
    }
    }
    datas.add(itemMap);
    }
    } catch (JSONException e) {
    }
    return datas;
    }

     

    方法21:保存Object或者ListObject (sharedPreferences+json)

    Sharepreference是Android常用的数据存储技术,以key-value保存在手机本地,经常只是用来保存基本类型数据,
    Google也只是提供putLong(),putBoolean(),putString()…实际项目中,我们经常是需要缓存Object或者ListObject,方便我们对App逻辑的操作,这时候我们就需要进一步封装,
    利用Gson把Object或者ListObject转成String,用putString()保存,需要展示缓存内容时,get到String,利用Gson转成Object或者ListObject.
    实际项目开发中,建议对Sharedpreference做成工具类,代码会简洁,直观。

    存储Object对象

    public void saveObject(String key, Object obj) {
    SharedPreferences.Editor edit = settings.edit();
    String str = gson.toJson(obj, obj.getClass());
    edit.putString(key, str);
    edit.commit();
    }

    获取存储Object对象

    public <T> T getObject(String key, Class<?> classItem) {
    try {
    String str = settings.getString(key, null);
    if (str != null) {
    return (T) gson.fromJson(str, classItem);
    }
    } catch (Exception e) {

    }

    存储ListObeject对象
    public <T> void saveListObject(String key, List<T> list) {
    SharedPreferences.Editor edit = settings.edit();
    String str = gson.toJson(list);
    edit.putString(key, str);
    edit.commit();
    }
    }


    获取ListObeject对象
    public List getListObject(String key,Class<?> classItem) {
    JavaType javaType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, classItem);
    try {
    String str = settings.getString(key, null);
    if (str != null) {
    return mapper.readValue(str,javaType);
    }
    } catch (Exception e) {

    }
    return null;
    }

    以上是我在实际开发中,Sharedpreference 对Object和ListObject封装,欢迎交流指正。

    方法2: 保存list( Json+SharedPrefernces ):

    先把PlayList对象转换为JSON形式的字符串,用SharedPreferences来保存字符串。
    /**
    * 把播放列表转换为JSON形式以字符串形式保存
    * @param object 播放列表对象
    */
    public static void getJsonStringByEntity(Context context, Object object) {
    String strJson = "";
    Gson gson = new Gson();
    strJson = gson.toJson(object);
    saveSharePlayList(context,strJson);
    }

    读取出来的:
    /**
    * 读取播放列表数据
    */
    public static PlayList getfromJson(Context context){
    PlayList list = null;
    String str = readSharePlayList(context);
    if(str!=null){
    Gson gson=new Gson();
    list = gson.fromJson(str, new TypeToken<PlayList>(){}.getType());
    }
    return list;
    }

     

     

    方法1:依赖包:

    直接转成String后再转回来降低了效率,这里有一个存储简单对象的编译时注解库:
    https://github.com/2tu/fit 。
    Fit 使用SharedPreferences存储对象中的基本数据类型。利用APT编译时生成代码,与转成String及反射相比更快。
    支持:基本类型,基本包装类型,Set,minSDK 11。

     

  • 相关阅读:
    coder的脚印
    Mysql
    MSDos
    Windows Develop
    Eclipse 使用总结
    DBA常用SQL
    SSH总结
    Unity3D协程
    yield的作用
    UGUI优化
  • 原文地址:https://www.cnblogs.com/awkflf11/p/6024147.html
Copyright © 2011-2022 走看看