0

我有一个有 2 个属性的类。一个属性是 HttpResponseMessage,我需要对其进行序列化。我在类上做了一个 [DataContract],在 HttpResponse 上做了一个 [DataMember]。这是课程:

[DataContract]
public class ResponseItem
{
    [DataMember]
    public HttpResponseMessage ResponseMessage { get; set; }
    [DataMember]
    public CacheInfoItem CacheInfo { get; set; }
}

问题是当我测试它然后我得到这个错误:

An exception of type 'System.Runtime.Serialization.InvalidDataContractException' occurred 
in mscorlib.dll but was not handled in user code
Additional information: Type 'System.Net.Http.StreamContent' cannot be serialized. 
Consider marking it with the DataContractAttribute attribute, and marking all of its 
members you want serialized with the DataMemberAttribute attribute.  If the type is a    
collection, consider marking it with the CollectionDataContractAttribute.  See the Microsoft 
.NET Framework documentation for other supported types.

怎么了?

编辑:我有一个保存方法:

public static async Task SaveObjectAsync(Object toBeSaved, string fileName = null, 
StorageLocation storageLocation = StorageLocation.Local, SerializerType serializerType = 
SerializerType.DataContractJson)
    {
        Type type = toBeSaved.GetType();
        fileName = getFileName(fileName, type, serializerType);
        StorageFolder folder = getStorageFolder(storageLocation);
        MemoryStream memoryStream = new MemoryStream();
        Serializer serializer = getSerializer(serializerType, type);
        serializer.WriteObject(memoryStream, toBeSaved);
        StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
        using (Stream fileStream = await file.OpenStreamForWriteAsync())
        {
            memoryStream.Seek(0, SeekOrigin.Begin);
            await memoryStream.CopyToAsync(fileStream);
            await fileStream.FlushAsync();
        }
    }

但看起来序列化程序无法处理 HttpResponseMessage

4

1 回答 1

0

[Serialize]在类之上添加以使其可序列化。

编辑:不知道它适用于 Win RT。在这种情况下,您需要创建 serialize-helper 类:

使用这个类作为序列化类:

class LocalStorage
{
    private static List<object> _data = new List<object>();


    public static List<object> Data
    {
        get { return _data; }
        set { _data = value; }
    }

    private const string filename = "cats.xml";

    static async public Task Save<T>()
    {
        await Windows.System.Threading.ThreadPool.RunAsync((sender) => LocalStorage.SaveAsync<T>().Wait(), Windows.System.Threading.WorkItemPriority.Normal);
    }

    static async public Task Restore<T>()
    {
            await Windows.System.Threading.ThreadPool.RunAsync((sender) => LocalStorage.RestoreAsync<T>().Wait(), Windows.System.Threading.WorkItemPriority.Normal);
    }

    static async private Task SaveAsync<T>()
    {
        StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
        IRandomAccessStream sessionRandomAccess = await sessionFile.OpenAsync(FileAccessMode.ReadWrite);
        IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
        var sessionSerializer = new DataContractSerializer(typeof(List<object>), new Type[] { typeof(T) });
        sessionSerializer.WriteObject(sessionOutputStream.AsStreamForWrite(), _data);
        await sessionOutputStream.FlushAsync();
    }

    static async private Task RestoreAsync<T>()
    {
        StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
        if (sessionFile == null)
        {
            return;
        }
        IInputStream sessionInputStream = await sessionFile.OpenReadAsync();
        var sessionSerializer = new DataContractSerializer(typeof(List<object>), new Type[] { typeof(T) });
        _data = (List<object>)sessionSerializer.ReadObject(sessionInputStream.AsStreamForRead());
    }
}

以及使用辅助类的基本代码:

namespace SerializeListWinRT
{

public sealed partial class MainPage : Page
{
    private readonly ObservableCollection<Cat> _cats = new ObservableCollection<Cat>();

    public ObservableCollection<Cat> Cats
    {
        get { return _cats; }
    }

    public MainPage()
    {
        this.InitializeComponent();
        ClearLists();
        AddCatsToList();
        CreateNewCat();
    }

    private async void AddCatsToList()
    {
        await LocalStorage.Restore<Cat>();
        SetCatList();
    }

    private void ClearLists()
    {
        Cats.Clear();
        LocalStorage.Data.Clear();
    }

    private void SetCatList()
    {
        foreach (var item in LocalStorage.Data)
        {
            _cats.Add(item as Cat);
        }
    }

    public Cat NewCat { get; set; }

    private void CreateNewCat()
    {
        NewCat = new Cat();
    }

    private void AddNewCat()
    {
        _cats.Add(new Cat {Name = NewCat.Name, About = NewCat.About});
    }
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        AddNewCat();
    }

    private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        AddNewCat();
        SaveList();
    }

    private void SaveList()
    {
        LocalStorage.Data.Add(NewCat);
        LocalStorage.Save<Cat>();
    }

}
}

序列化LocalStorage.Save<Cat>();并保存它,这听起来像你想要的。

参考:http: //irisclasson.com/2012/07/09/example-metro-app-winrt-serializing-and-deseralizing-objects-to-storagefile-and-localfolder-using-generics-and-asyncawait-threading/

于 2013-08-28T07:49:58.793 回答