Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

c# - Newtonsoft Json.net - how to serialize content of a stream?

I need to convert to JSON arbitrary content of a memory stream. Here is a quick example of what I am trying to do:

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();
    }
}

Not sure what to pass to the SerializeObject method. If I pass the MemoryStream (variable ms) I get an error:

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

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

Is that possible to serialize arbitrary content of a stream ?

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...