SharePrecences--(json+sharePrecences)存list 或對象

來源:互聯網
上載者:User

標籤:比較   username   repr   odi   str   exce   base   final   min   

 

利用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對象。

 

 

 

方法21:SharedPreferences+JsonArray 儲存List(Map(String, String))

原因:
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;
}

 

方法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儲存物件中的基礎資料型別 (Elementary Data Type)。利用APT編譯時間產生代碼,與轉成String及反射相比更快。
支援:基本類型,基本封裝類型,Set,minSDK 11。

 

SharePrecences--(json+sharePrecences)存list 或對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.