在内部,JsonConvert.SerializeObject(obj, Formatting.Indented)
归结为
JsonSerializer jsonSerializer = JsonSerializer.Create(null);
StringWriter stringWriter = new StringWriter(new StringBuilder(256), (IFormatProvider) CultureInfo.InvariantCulture);
using (JsonTextWriter jsonTextWriter = new JsonTextWriter((TextWriter) stringWriter))
{
jsonTextWriter.Formatting = formatting;
jsonSerializer.Serialize((JsonWriter) jsonTextWriter, value);
}
return stringWriter.ToString();
这样很好。但是,如果我执行以下操作:
string json;
JsonSerializer jsonSerializer = JsonSerializer.Create();
using (var stream = new MemoryStream())
using (var streamWriter = new StreamWriter(stream, Encoding.UTF8))
using (var jsonWriter = new JsonTextWriter(streamWriter))
{
serializer.Serialize(jsonWriter, cmd);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
json = reader.ReadToEnd();
}
}
那么
json
的值为""
。谁能指出我的错误? 最佳答案
问题是您没有在编写后刷新streamWriter
:
serializer.Serialize(jsonWriter, cmd);
streamWriter.Flush();
stream.Position = 0;
另外,为什么不只使用
StringWriter
开头呢?using (var writer = new StringWriter())
{
using (var jsonWriter = new JsonTextWriter(writer))
{
serializer.Serialize(jsonWriter, cmd);
Console.WriteLine(writer.ToString());
}
}
关于c# - Json.Net无法序列化为流,但是可以很好地序列化为字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9845741/