HttpResponseMessage serialization
本文关键字:serialization HttpResponseMessage | 更新日期: 2023-09-27 18:29:12
我有一个具有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
在类的顶部添加[Serialize]
以使其可序列化。
EDIT:不知道这是为Win-RT。在这种情况下,你需要创建序列化助手类:
将此类用作序列化类:
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/