使用JSON进行序列化

时间:2016-10-04 08:21:06

标签: c# json serialization uwp

我需要序列化几个属性。我使用NewtonSoft的Json序列化器

我的代码:

<ng-content>

我在磁盘上有文件,但是当我尝试反序列化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.

我的问题是什么?

2 个答案:

答案 0 :(得分:1)

您的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)

答案 1 :(得分:0)

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