Storing serialized data on local storage with PCL

BrunoBarcellosBrunoBarcellos USMember
edited November 2016 in Xamarin.Forms

So, I'm trying to save some data on local storage for when the user is not online, this working on my portable class.
First I got it working partly using XML serialization, but as I discovered on my tests, XML doesn't like too much TimeSpan... So I had to move on to another solution, but stick with the same logic with a DataStorageService(linkhere) class to manage serialization and saving.

After my failed attempt to serialize in XML, now I'm trying to do with JSON. I'm using System.Runtime.Serialization.Json; since System.Web.... is not available in PCL. As for saving I'm using PCLStorage;
parameters(String Key, T ValueToSave)

Serialization :
var ms = new MemoryStream(); var js = new DataContractJsonSerializer(typeof(T)); js.WriteObject(ms, ValueToSave); IFolder rootFolder = FileSystem.Current.LocalStorage; IFolder folder = await rootFolder.CreateFolderAsync("Cache", CreationCollisionOption.OpenIfExists); IFile file = await folder.CreateFileAsync(Key + ".json", CreationCollisionOption.ReplaceExisting); StreamReader sr = new StreamReader(ms); await file.WriteAllTextAsync(sr.ReadToEnd());

Deserialization :
IFile file = await folder.CreateFileAsync(Key + ".json", CreationCollisionOption.OpenIfExists); string jsstring = await file.ReadAllTextAsync(); DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsstring)); return (T)js.ReadObject(ms);

Serializing gives me no error but Deserializing gives me :
"Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''."

I don't mind XML, JSON or binary for saving the object. I just want the data to be written and read from local storage.

Best Answer


  • SKallSKall USMember ✭✭✭✭

    Sounds like a type mismatch. Are you sure the type T is the same for both serialization and deserialization? For debug reasons I would start by outputting the text to debug console on both methods.

  • rolfMrolfM ATMember ✭✭

    Sorry for bringing up this post again but did you ever managed to get your data to an xml file? Or is Json the only way in PCL?

Sign In or Register to comment.