Java convert ArrayList to string and back to ArrayList?

后端 未结 6 1373
一个人的身影
一个人的身影 2020-12-29 11:30

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
Shared         


        
6条回答
  •  旧时难觅i
    2020-12-29 11:49

    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);
      

提交回复
热议问题