2015-05-19 67 views
2

我需要將內存流的任意內容轉換爲JSON 。以下是我正在嘗試執行的一個快速示例:Newtonsoft Json.net - 如何序列化流的內容?

class Program 
{ 
    class TestClass { public int Test1;} 
    static void Main(string[] args) 
    { 
     var ms = new MemoryStream(); 
     var writer = new StreamWriter(ms); 
     writer.Write(new TestClass()); 
     writer.Flush(); 
     ms.Position = 0; 

     var json = JsonConvert.SerializeObject(/*???*/, Formatting.Indented); 
     Console.Write(json); 
     Console.Read(); 
    } 
} 

不確定傳遞給SerializeObject方法的是什麼。如果我通過將MemoryStream(可變MS)我得到一個錯誤:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll

Additional information: Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.

這是可能的序列化流的任意內容?

謝謝您可以使用轉換器來實現一個MemoryStream的

+1

你可以序列化由'MemoryStream.ToArray()'返回的'byte []'。 Json.NET會將其序列化爲[base 64 encoded string](http://www.newtonsoft.com/json/help/html/SerializationGuide.htm)。 – dbc

+0

看到這個答案http://stackoverflow.com/questions/8157636/can-json-net-serialize-deserialize-to-from-a-stream – EdmundYeung99

回答

7

序列化和反序列化內容:

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); 
    } 
+0

優秀的解決方案。這應該被接受爲答案。 –