Xamarin Essentials Save Object Details

625 Views Asked by At

I'm looking for a good way to save a list of details into Xamarin.Essentials.Preferences.

Basically something like

<Item>
    <Name>Toast</Name>
    <Weight>0.5oz</Weight>
    <Quantity>4</Quantity>
</Item>

I thought of doing some xml serialization but I'm not sure that's the best approach.

This list will be less than 500 items, with as many as 6 attributes per item, Name, Weight, Quantity, ImageRefPath, etc.

Anyone have any suggestions and/or examples of a good way to store this?

Things that won't exist in the Items collection are:

No binary data. No Images. No BLOBS.

1

There are 1 best solutions below

2
On

Maybe you could try to convert the items to a json string.Then save it to Xamarin.Essentials.Preferences.

For example,define a model first:

public class MyItem
{
    public string Name { get; set; }
    public string Weight{ get; set; }
    public string Quantity{get;set;}
    public string ImageRefPath{get;set;}
    ...
}

//convert the items data to json string and save
ObservableCollection<MyItem> ItemList;
string json = JsonConvert.SerializeObject(ItemList);
Xamarin.Essentials.Preferences.Set("list", json);

//get the json string then convert to the List<MyItem>.
string json = Xamarin.Essentials.Preferences.Get("list","");
ObservableCollection<MyItem> items = JsonConvert.DeserializeObject<ObservableCollection<MyItem>>(json );