将arraylist从字符串转换为arraylist

时间:2019-04-14 15:06:07

标签: java android arrays json sharedpreferences

要使用JSON在Android Studio上存储数组列表,它会转换为字符串,因此在检索它时,我需要将其转换回数组列表。 arraylist包含对象。还是有一种方法可以将具有共享首选项的数组列表存储为数组列表而不是字符串。

SharedPreferences accountReader = getSharedPreferences("storedAccounts",MODE_PRIVATE);
SharedPreferences.Editor accountEditor = getSharedPreferences("storedAccounts",0).edit();

ArrayList<userAccount> accountsList = new ArrayList<userAccount>();

Gson gson = new Gson();
String json = accountReader.getString("accounts","");

if(json.isEmpty() == false){ 
   //repopulate accountsList with the stored values 
}

userAccount newEntry = new userAccount();
newEntry.id = id;
newEntry.username = username;
newEntry.password = password;
newEntry.url = url;
newEntry.note = note;

accountsList.add(newEntry);

Gson gsonTwo = new Gson();

String jsonTwo = gsonTwo.toJson(accountsList);
accountEditor.putString("accounts",jsonTwo);
accountEditor.apply();
accountEditor.commit();

1 个答案:

答案 0 :(得分:0)

您可以尝试类似

List<String> yourList = new ArrayList<String>(Arrays.asList(yourString.split(",")))