序列化和反序列化內容:
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);
}
}
那麼你的代碼可能看起來像(我改變了「新識別TestClass()」,以「測試字符串」爲JSON序列和反串行化)的更容易的比較:
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();
}
這種轉換器,也可以使用當流是串行化obj的一個屬性等:
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);
}
你可以序列化由'MemoryStream.ToArray()'返回的'byte []'。 Json.NET會將其序列化爲[base 64 encoded string](http://www.newtonsoft.com/json/help/html/SerializationGuide.htm)。 – dbc
看到這個答案http://stackoverflow.com/questions/8157636/can-json-net-serialize-deserialize-to-from-a-stream – EdmundYeung99