我有一个程序的示例:
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: ()
}
}
}
it 应该(根据此页面:https://www.newtonsoft.com/json/help/html/serializedjson.htm)制作一个包含对象的JSON表示的流:obj
但实际上,该流似乎具有长度0
,并且是写出时的一个空字符串。我该怎么做才能实现正确的序列化?
以下是运行程序的示例:https://dotnetfiddle.net/pi1bqe
您需要冲洗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();