Java convert ArrayList to string and back to ArrayList?

末鹿安然 提交于 2019-12-20 12:28:51

问题


I wanted to save an ArrayList to SharedPreferences so I need to turn it into a string and back, this is what I am doing:

// Save to shared preferences
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("myAppsArr", myAppsArr.toString());
editor.commit();

I can retrieve it with String arrayString = sharedPref.getString("yourKey", null); but I don't know how to convert arrayString back into an ArrayList. How can it be done?


My array looks something like:

[item1,item2,item3]

回答1:


You have 2 choices :

  1. Manually parse the string and recreate the arraylist. This would be pretty tedious.
  2. Use a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,

    // How to store JSON string
    Gson gson = new Gson();
    // This can be any object. Does not have to be an arraylist.
    String json = gson.toJson(myAppsArr);
    
    // How to retrieve your Java object back from the string
    Gson gson = new Gson();
    DataObject obj = gson.fromJson(arrayString, ArrayList.class);
    



回答2:


Try this

ArrayList<String> array = Arrays.asList(arrayString.split(","))

This will work if comma is used as separator and none of the items have it.




回答3:


      //arraylist convert into String using Gson 
      Gson gson = new Gson();
      String data = gson.toJson(myArrayList);
      Log.e(TAG, "json:" + gson);

      //String to ArrayList

      Gson gson = new Gson();
      arrayList=gson.fromJson(data, new TypeToken<List<Friends>>()
      {}.getType());



回答4:


I ended up using:

ArrayList<String> appList = new ArrayList<String>(Arrays.asList(appsString.split("\\s*,\\s*")));

This doesn't work for all array types though. This option differs from:

ArrayList<String> array = Arrays.asList(arrayString.split(","));

on that the second option creates an inmutable array.




回答5:


The page http://mjiayou.com/2015/07/22/exception-gson-internal-cannot-be-cast-to/ contains the following:

Type     type  = new TypeToken<List<T>>(){}.getType();
List<T>  list  = gson.fromJson(jsonString, type)

perhaps it will be helpful.




回答6:


Update to Dhruv Gairola's answer for Kotlin

val gson = Gson();
val jsonString = gson.toJson(arrayList) 


来源:https://stackoverflow.com/questions/12276205/java-convert-arraylist-to-string-and-back-to-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!