簡體   English   中英

JSON序列化

[英]Serializing with JSON

我需要序列化幾個屬性。 我使用NewtonSoft的Json序列化器

我的代碼:

   [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; }
}

我的磁盤上有文件,但是當我嘗試反序列化json時出現錯誤。 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文件

[{"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}}}]

我怎么了

您的JSON文件無效/不完整。

[
    {
        "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.

您正在創建文件,但沒有刷新/關閉文件。

var sampleFile = await storageFolder.CreateFileAsync("MyProject.Collage",    CreationCollisionOption.ReplaceExisting);
 string l =JsonConvert.SerializeObject(this.ImageList);
await FileIO.WriteTextAsync(sampleFile, l); // <== no FileIO.Close(sampleFile)
      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);
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM