Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 尝试使用Newtonsoft将对象序列化为流,得到一个空流_C#_Serialization_Stream_Json.net - Fatal编程技术网

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

C# 尝试使用Newtonsoft将对象序列化为流,得到一个空流,c#,serialization,stream,json.net,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 write

我有一个程序示例:

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: ()
        }
    }
}
它应该(根据本页:)生成一个包含对象的JSON表示的流:
obj
,但实际上该流的长度似乎为
0
,并且在写出时是一个空字符串。如何实现正确的序列化


下面是一个运行程序的示例:

您需要刷新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() + ")");
    }
}

你需要刷新你的作家

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

请您在问题中链接到小提琴的叉子,说明这是如何做到的,好吗?非常感谢!还意识到您需要对writer调用Flush(),以使其写入实际内存流,因为它在写入数据之前会缓存一些数据。@stuartd尝试一下,看看您是否确实需要重置位置!两者都是必需的。