我試圖在 SharedPreferences 中保存一個物件,但首先將物件轉換為 JSON,如下所示。但是,物件被錯誤地轉換和保存。
private void saveHobbySchedule() {
String jsonString = new Gson().toJson(hobbySchedule);
Log.e("Saving Hobby Schedule: ", jsonString);
SharedPreferences sharedPreferences = getSharedPreferences("UserData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("hobbySchedule", jsonString);
editor.apply();
}
JSON 如下所示:
E/Saving Hobby Schedule:: {"com.example.hobbie.ObjectModels.Hobby@a64126":["MONDAY @ 15:36","WEDNESDAY @ 15:36","THURSDAY @ 15:36"]}
這使得無法保存和檢索hobbySchedule變數。
如果有幫助,hobbySchedule可以像這樣宣告和初始化:
LinkedHashMap<Hobby, ArrayList<String>> hobbySchedule = new LinkedHashMap<>();
這也是 Hobby 類的代碼。
public class Hobby implements Serializable {
private final String hobbyName;
private final String hobbyEmoji;
private final String hobbyCategory;
private final String hobbyDescription;
private final String hobbyShortDescription;
private final String hobbyPracticeLocation;
private final String hobbyImageURL;
public Hobby() {
this.hobbyName = "";
this.hobbyEmoji = "";
this.hobbyCategory = "";
this.hobbyDescription = "";
this.hobbyShortDescription = "";
this.hobbyPracticeLocation = "";
this.hobbyImageURL = "";
}
public Hobby(String hobbyName, String hobbyEmoji, String hobbyCategory, String hobbyDescription,
String hobbyShortDescription, String hobbyPracticeLocation, String hobbyImageURL) {
this.hobbyName = hobbyName;
this.hobbyEmoji = hobbyEmoji;
this.hobbyCategory = hobbyCategory;
this.hobbyDescription = hobbyDescription;
this.hobbyShortDescription = hobbyShortDescription;
this.hobbyPracticeLocation = hobbyPracticeLocation;
this.hobbyImageURL = hobbyImageURL;
}
為什么 Hobby 檔案地址的名稱被轉換為 JSON 并保存而不是值?請幫忙,謝謝!
uj5u.com熱心網友回復:
JSON 僅支持字串作為 JSON 物件屬性名稱。因此 Gson 默認呼叫該toString()方法將非字串Map鍵轉換為字串。
如果您的Hobby類的實體可以輕松表示為字串,則您可以覆寫其toString()方法。但是,對于反序列化,您可能必須注冊自定義TypeAdapter.
否則,您可以使用GsonBuilder.enableComplexMapKeySerialization()which 將序列Map化為 JSON 陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/382579.html
上一篇:將HTML檔案放在Android應用程式資源檔案中的何處以及如何放置?
下一篇:抽象類BaseVMActivity<VM:ViewModel,B:ViewBinding>和抽象類BaseVMActivity(VM:ViewModel,B:ViewBinding)的區別
