将数据序列化为json文件时出错

将数据序列化为json文件时出错

我有这个课:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace PushUpApp
{
    [DataContract]
    public class PushUps
    {
        [DataMember]
        public int TotalReps { get; set; }
        [DataMember]
        public DateTime Day { get; set; }
        public PushUps(int _totalReps,DateTime _day)
        {
            TotalReps = _totalReps;
            Day = _day;
        }
    }
}


和这种方法:

public async Task writePushUpsAsync()
    {
        var jsonSerializer = new DataContractJsonSerializer(typeof(PushUps));
        using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(FILE, CreationCollisionOption.ReplaceExisting))
        {
            jsonSerializer.WriteObject(stream, _pushUps);
        }
    }

private async void FinishButton_Click(object sender, RoutedEventArgs e)
    {
        PushUps _pushUp = new PushUps(reps, _day);
        if (_pushUps.Count!=0)
        {
            PushUps CurrentDayPushUp = _pushUps.Last();
            if (CurrentDayPushUp.Day.Day == _pushUp.Day.Day && CurrentDayPushUp.Day.Year == _pushUp.Day.Year && CurrentDayPushUp.Day.Month == _pushUp.Day.Month)
            {
                _pushUps.Last().TotalReps += _pushUp.TotalReps;
            }
            else
            {
                _pushUps.Add(_pushUp);
            }
        }
        else
            _pushUps.Add(_pushUp);
        await writePushUpsAsync();
    }


我得到这个错误

An exception of type
'System.Runtime.Serialization.SerializationException'
occurred in mscorlib.ni.dll but was not handled in user code

Additional information: Type
'System.Collections.Generic.List`1[[PushUpApp.PushUps,
PushUpApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'
with data contract name
'ArrayOfPushUps:http://schemas.datacontract.org/2004/07/PushUpApp'
is not expected. Add any types not known statically to the list of
known types - for example, by using the KnownTypeAttribute attribute
or by adding them to the list of known types passed to
DataContractSerializer.


我该怎么办?

最佳答案

我猜_pushUps是某种列表?可能是List<PushUps>类型还是类似的? (这是因为我看到了_pushUps.Add(_pushUp)

如果是这种情况,那么您只需要更新DataContractJsonSerializer即可使用列表类型,而不是单个类。因此,将writePushUpsAsync中的行更改为如下所示:

var jsonSerializer = new DataContractJsonSerializer(typeof(List<PushUps>));


这就是错误的含义-它收到了意外的列表,而不是单个项目。

关于c# - 将数据序列化为json文件时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38684243/

10-13 03:14