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)
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());
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.