Reputation: 311
I need serialize couple properties. I use Json serializer from NewtonSoft
My code:
[DataContract]
public class ImageManipulatorViewModel : BaseViewModel
{
[DataMember]
public ObservableCollection<Collage> ImageList
{
get { return this.imageList; }
set
{
this.imageList = value;
base.RaisePropertyChanged("ImageList");
}
}
var storageFolder = ApplicationData.Current.LocalFolder;
var sampleFile = await storageFolder.CreateFileAsync("MyProject.Collage", CreationCollisionOption.ReplaceExisting);
string l =JsonConvert.SerializeObject(this.ImageList);
await FileIO.WriteTextAsync(sampleFile, l);
string tres = JsonConvert.DeserializeObject(l).ToString();
this.ImageList.Clear();
this.ImageList = JsonConvert.DeserializeObject<ObservableCollection<Collage>>(tres.ToString());
}
public class Collage
{
public Thickness Position { get; set; }
public WriteableBitmap Image { get; set; }
}
I have file on disk, but when I try deserialize json I have an error.
Could not create an instance of type Windows.Storage.Streams.IBuffer. Type is an interface or abstract class and cannot be instantiated. Path '[0].Image.PixelBuffer', line 10, position 23.
JSON file
[{"Position":{"Left":0.0,"Top":0.0,"Right":0.0,"Bottom":0.0},"Image":{"PixelBuffer":{},"PixelHeight":1600,"PixelWidth":2560,"Dispatcher":{"HasThreadAccess":true,"CurrentPriority":0}}},{"Position":{"Left":490.0,"Top":0.0,"Right":0.0,"Bottom":0.0},"Image":{"PixelBuffer":{},"PixelHeight":1600,"PixelWidth":2560,"Dispatcher":{"HasThreadAccess":true,"CurrentPriority":0}}}]
What`s my problem?
Upvotes: 0
Views: 133
Reputation: 311
var savePicker = new FileSavePicker
{
SuggestedStartLocation = PickerLocationId.PicturesLibrary,
SuggestedFileName = string.Format("MyProject{0}", DateTime.Now.ToString("ddMMyyyyHHmm"))
};
savePicker.FileTypeChoices.Add("Project", new List<string> {".collage"});
var file = await savePicker.PickSaveFileAsync();
if (file != null)
{
var ser = JsonConvert.SerializeObject(this.ImageList.ToList());
await FileIO.WriteTextAsync(file, ser);
}
Upvotes: 0
Reputation: 15465
Your JSON file is not valid / complete.
[
{
"Position": {"Left":0.0,"Top":0.0,"Right":0.0,"Bottom":0.0},
"Image":{
"PixelBuffer": {},
"PixelHeight":1600,
"PixelWidth":2560,
"Dispatcher":{"HasThreadAccess":true,"CurrentPriority":0}
}
}, <=== here it ends without a following item or closing the array.
You are creating a file but you are not flushing / closing it.
var sampleFile = await storageFolder.CreateFileAsync("MyProject.Collage", CreationCollisionOption.ReplaceExisting);
string l =JsonConvert.SerializeObject(this.ImageList);
await FileIO.WriteTextAsync(sampleFile, l); // <== no FileIO.Close(sampleFile)
Upvotes: 1