As you design your web API, it is useful to test how your data objects will be serialized. You can do this without creating a controller or invoking a controller action.
在设计Web API时,对如何序列化对象进行测试是有用的。不必创建控制器或调用控制器动作,便可做这种事。
string Serialize<T>(MediaTypeFormatter formatter, T value)
{
// Create a dummy HTTP Content.
// 创建一个HTTP内容的哑元
Stream stream = new MemoryStream();
var content = new StreamContent(stream);
// Serialize the object.
// 序列化对象
formatter.WriteToStreamAsync(typeof(T), value, stream, content.Headers, null).Wait();
// Read the serialized string.
// 读取序列化的字符串
stream.Position = 0;
return content.ReadAsStringAsync().Result;
}
T Deserialize<T>(MediaTypeFormatter formatter, string str) where T : class
{
// Write the serialized string to a memory stream.
// 将序列化的字符器写入内在流
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(str);
writer.Flush();
stream.Position = 0;
// Deserialize to an object of type T
// 解序列化成类型为T的对象
return formatter.ReadFromStreamAsync(typeof(T), stream, null, null).Result as T;
}
// Example of use
// 使用示例(用例)
void TestSerialization()
{
var value = new Person() { Name = "Alice", Age = 23 };
var xml = new XmlMediaTypeFormatter();
string str = Serialize(xml, value);
var json = new JsonMediaTypeFormatter();
str = Serialize(json, value);
// Round trip
// 反向操作(解序列化)
Person person2 = Deserialize<Person>(json, str);
}
看完此文如果觉得有所收获,请给个。
你的推荐是我继续下去的动力,也会让更多人关注并获益,这也是你的贡献。