尝试使用Newtonsoft将对象序列化为流,得到空流

时间:2019-03-15 14:02:16

标签: c# serialization stream json.net

我有一个程序示例:

using System;
using Newtonsoft.Json;
using System.IO;

public class Program
{
    public static void Main()
    {
        using (var stream = new MemoryStream())
        using (var reader = new StreamReader(stream))
        using (var writer = new StreamWriter(stream))
        using (var jsonWriter = new JsonTextWriter(writer))
        {
            new JsonSerializer().Serialize(jsonWriter, new { name = "Jamie" });
            Console.WriteLine("stream length: " + stream.Length); // stream length: 0
            Console.WriteLine("stream position: " + stream.Position); // stream position: 0
            Console.WriteLine("stream contents: (" + reader.ReadToEnd() + ")"); // stream contents: ()
        }
    }
}

(应根据此页面:https://www.newtonsoft.com/json/help/html/SerializingJSON.htm(<本页> {obj的JSON表示的流,但实际上,该流似乎具有长度{ {1}},写出时为空字符串。我该怎么做才能实现正确的序列化?

以下是程序正在运行的示例:https://dotnetfiddle.net/pi1bqE

2 个答案:

答案 0 :(得分:1)

您需要刷新JsonSerializer,以确保它实际上已将数据写入基础流。流将在结束位置,因此您需要将其倒回开始位置以读取数据。

public static void Main()
{
    using (var stream = new MemoryStream())
    using (var reader = new StreamReader(stream))
    using (var writer = new StreamWriter(stream))
    using (var jsonWriter = new JsonTextWriter(writer))
    {
        new JsonSerializer().Serialize(jsonWriter, new { name = "Jamie" });

        jsonWriter.Flush();
        stream.Position = 0;

        Console.WriteLine("stream contents: (" + reader.ReadToEnd() + ")");
    }
}

答案 1 :(得分:1)

您需要冲洗作家。

new JsonSerializer().Serialize(jsonWriter, new { name = "Jamie" });
jsonWriter.Flush();