简体   繁体   English

HttpResponseMessage序列化

[英]HttpResponseMessage serialization

I have a class with 2 attributes. 我有一类2属性。 One attribute is a HttpResponseMessage and I need to serialize this. 一个属性是HttpResponseMessage,我需要对其进行序列化。 I hade made a [DataContract] over the class and a [DataMember] over the HttpResponse. 我在类上做了一个[DataContract],在HttpResponse上做了一个[DataMember]。 Here is the class: 这是课程:

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

the problem is when I test it then I get this error: 问题是当我测试它时,我得到这个错误:

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.

what is wrong? 怎么了?

EDIT: I have a save method: 编辑:我有一个保存方法:

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

but it looks that the serializer can't handle the HttpResponseMessage 但看起来序列化程序无法处理HttpResponseMessage

Add [Serialize] on top of the class to make it serializable. 在类的顶部添加[Serialize]以使其可序列化。

EDIT: Did not know it's for Win RT. 编辑:不知道它是为Win RT。 In that case you need to create serialize-helper class: 在这种情况下,您需要创建serialize-helper类:

Use this class as the serialized-class: 将此类用作序列化类:

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

And the essential code to use the helper class: 以及使用helper类的基本代码:

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

}
}

The LocalStorage.Save<Cat>(); LocalStorage.Save<Cat>(); serializes and saves it, which sounds like what you want. 序列化并保存它,听起来像您想要的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM