我是使用NewtonSoft.Json库的新手,并且有一个关于将JSON直接编写到Response.OutputStream
的问题(因为我从阅读文档的理解是这将是返回大型JSON对象的最有效方法)...
以下是小代码段:
sw = Nothing
jw = Nothing
Try
sw = New System.IO.StreamWriter( Response.OutputStream )
jw = New Newtonsoft.Json.JsonTextWriter( sw )
jw.WriteStartObject()
jw.WritePropertyName( "name" )
jw.WriteValue( "value" )
jw.WriteEndObject()
Catch ex As Exception
err_msg = ex.ToString()
Finally
If ( jw isNot Nothing ) Then
jw.Close()
jw = Nothing
End If
End Try
' Is Response.OutputStream closed as well at this point?
' Would a call to Response.Write( "anything" ) fail because the OutputStream would be closed?
如上面的评论所示,我的问题是:
调用JsonTextWriter.Close()
方法时,这是否也会关闭Response.OutputStream
?
只是想确保我正确地写入响应流而不会无意中破坏它,我应该在事后做Response.Write()
。
答案 0 :(得分:2)
是的,默认情况下,JsonTextWriter.Close()
会在基础Close
上调用TextWriter
,如果它是StreamWriter
,则会调用Close
在底层流上。但是,您可以将JsonTextWriter
上的CloseOutput
属性设置为false
以防止此情况发生。