将数据保存在本地存储

Save data on local storage

我正在使用 Xamarin Forms 开发应用程序 PCL。

我想保存这个class(我在代码中使用这个class作为列表)

public class TagInformation {
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string name { get; set; }
    public bool isJob { get; set; }
    public string _color { get; set; }
    [Ignore]
    public Color color { get; set; }
    [Ignore]
    public JobInformation jobInformation { get; set; }

    public TagInformation(Color c, string n) {
        color = c;
        _color = c.ToHex();
        name = n;
        isJob = false;
    }
    public TagInformation() {
    }
    public void setColor() {
        color = Color.FromHex(_color);
    }
}

public class JobInformation {
    public string shopName { get; set; }
    public int wage { get; set; }
    public bool isHoliday { get; set; }
    public int holidayWage { get; set; }
    public bool isMid { get; set; }
    public int midnightWage { get; set; }
    public bool[] holidayFlgs { get; set; }
    public DateTime midStart { get; set; }
    public DateTime midEnd { get; set; }
    public int tranceportCost { get; set; }
    public int closeDay { get; set; }
    public int payMentDay { get; set; }
    public TimeSpan shortRest { get; set; }
    public TimeSpan longRest { get; set; }
    public TimeSpan shortRestTime { get; set; }
    public TimeSpan longRestTime { get; set; }
    public TimeSpan commuteTime { get; set; }
    public JobInformation() {
        /* do samething */
    }
}

使用 SQLite,这个 class 有另一个 class,所以它不能工作。

还有其他方法吗?

你有什么想法吗?

您可以尝试使用 Xamarin.Essentials: Preferences 将其保存为 json 字符串。

1.Install Newtonsoft.Json nuget.

2.Serialize 您的 class 到 json 字符串并用密钥保存。

TagInformation tarinformation = xxxxx;
string jsonString = JsonConvert.SerializeObject(tarinformation);
Preferences.Set("your_key", jsonString);  //save the data

3.Retrieve 来自首选项的值并反序列化字符串。

var myValue = Preferences.Get("my_key", "default_value");//get the data string
TagInformation infor = JsonConvert.DeserializeObject<TagInformation>(myValue); //deserialize to your class