序列化为json并作为流返回

时间:2018-10-10 20:19:38

标签: c# stream json.net

如何将对象序列化为json并将其作为流返回?

我尝试过:

        using (var stream = new MemoryStream())
        using (var streamWriter = new StreamWriter(stream))
        using (var jsonWriter = new JsonTextWriter(streamWriter))
        {
            var serializer = new JsonSerializer();
            serializer.Serialize(jsonWriter, obj);
            streamWriter.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }

但是流总是关闭的。

接下来我尝试过:

new MemoryStream(Convert.FromBase64String(JsonConvert.SerializeObject(obj)))

但这没有注册为base64字符串,我觉得此方法效率较低。

2 个答案:

答案 0 :(得分:3)

询问StreamWriter不会关闭您的流。当然,请避免流处理。

例如代码将是:

    var stream = new MemoryStream();
    using (var streamWriter = new StreamWriter(stream:stream, encoding:Encoding.UTF8, bufferSize:4096, leaveOpen:true)) // last parameter is important
    using (var jsonWriter = new JsonTextWriter(streamWriter))
    {
        var serializer = new JsonSerializer();
        serializer.Serialize(jsonWriter, obj);
        streamWriter.Flush();
        stream.Seek(0, SeekOrigin.Begin);
        return stream;
    }

另一个选择-避免关闭流,因为您不需要它(本地资源不会在此处泄漏):

    var stream = new MemoryStream();
    var streamWriter = new StreamWriter(stream)
    var jsonWriter = new JsonTextWriter(streamWriter)

    var serializer = new JsonSerializer();
    serializer.Serialize(jsonWriter, obj);
    jsonWriter.Flush();
    streamWriter.Flush();
    stream.Seek(0, SeekOrigin.Begin);
    return stream;

答案 1 :(得分:1)

Manushin的答案是正确的,即在返回第一个代码片段之前不关闭流。关于第二个片段,base 64编码与文本编码不同。要将字符串快速转换为内存流,可以使用Encoding.GetBytes(string)获取字节数组:

var jsonString = JsonConvert.SerializeObject(new { test = "123" });
return new MemoryStream(Encoding.Default.GetBytes(jsonString));