Serializing and deserializing content of a MemoryStream can be achieved using a converter:
public class MemoryStreamJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(MemoryStream).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var bytes = serializer.Deserialize<byte[]>(reader);
return bytes != null ? new MemoryStream(bytes) : new MemoryStream();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var bytes = ((MemoryStream)value).ToArray();
serializer.Serialize(writer, bytes);
}
}
Then your code could look like that (I changed "new TestClass()" to "Test string" for easier comparison of json serialization and deserialization):
private void CheckJsonSerialization()
{
var ms = new MemoryStream();
var writer = new StreamWriter(ms);
writer.WriteLine("Test string");
writer.Flush();
ms.Position = 0;
var json = JsonConvert.SerializeObject(ms, Formatting.Indented, new MemoryStreamJsonConverter());
var ms2 = JsonConvert.DeserializeObject<MemoryStream>(json, new MemoryStreamJsonConverter());
var reader = new StreamReader(ms2);
var deserializedString = reader.ReadLine();
Console.Write(json);
Console.Write(deserializedString);
Console.Read();
}
Such converter can be also used when Stream is a property of a serialized object:
public class ClassToCheckSerialization
{
public string StringProperty { get; set; }
[JsonConverter(typeof(MemoryStreamJsonConverter))]
public Stream StreamProperty { get; set; }
}
private void CheckJsonSerializationOfClass()
{
var data = new ClassToCheckSerialization();
var ms = new MemoryStream();
const string entryString = "Test string inside stream";
var sw = new StreamWriter(ms);
sw.WriteLine(entryString);
sw.Flush();
ms.Position = 0;
data.StreamProperty = ms;
var json = JsonConvert.SerializeObject(data);
var result = JsonConvert.DeserializeObject<ClassToCheckSerialization>(json);
var sr = new StreamReader(result.StreamProperty);
var stringRead = sr.ReadLine();
//Assert.AreEqual(entryString, stringRead);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…