本文介绍了Json.Net未能序列化到一个流,但工作得很好,序列化到一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在内部, 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();

这工作得很好。不过,如果我做到以下几点:

This works just fine. However, if I do the following:

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 的值是。任何人都可以点我的我的错?

Then the value of json is "". Can anyone point me to my mistake?

推荐答案

现在的问题是,你还没有被刷新的StreamWriter 写入后:

The problem is that you haven't flushed the streamWriter after writing:

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

这篇关于Json.Net未能序列化到一个流,但工作得很好,序列化到一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 15:12