[英]Reading JSON from SQL Server
I am having a SQL Query with multiple child FOR JSON Path with a final FOR JSON Path at the end. 我有一个带有多个子FOR JSON路径的SQL查询,最后有一个最终的FOR JSON路径。 The JSON being formed is relatively large.
形成的JSON相对较大。 However when I am trying to read the JSON from C# the JSON is not appearing properly.
但是,当我尝试从C#中读取JSON时,JSON不能正确显示。 C# code below to read the JSON from SQL Server
下面的C#代码从SQL Server读取JSON
var queryWithForJson = "EXEC TEST_SP";
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString);
var cmd = new SqlCommand(queryWithForJson, conn);
cmd.CommandTimeout = 0;
conn.Open();
var jsonResult = new StringBuilder();
var reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
reader.Close();
System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\file.json");
file.WriteLine(jsonResult.ToString());
The JSON file created is ending with: 创建的JSON文件以以下结尾:
"Det":[{"id":3700159,"address":"601 Union St Seattle, WA 98
As you can see the JSON did not end properly. 如您所见,JSON没有正确结束。 Any idea why this is happening?
知道为什么会这样吗?
Use a using
statement on your file. 在文件上使用
using
语句。 I replicated your issue when I didn't do this. 我没有这样做时就复制了您的问题。
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\file.json"))
{
file.Write(jsonResult.ToString());
}
After looking into this a bit more, it looks like you would also get the correct results if you flushed the StreamWriter. 在仔细研究了一下之后,如果刷新了StreamWriter,看起来您也会获得正确的结果。 You could do that with
file.AutoFlush = true;
您可以使用
file.AutoFlush = true;
or with file.Flush();
或与
file.Flush();
. 。 However you choose to accomplish this, you really should have a using statement around your StreamWriter anyway to be sure it is disposed of correctly.
无论您选择完成此操作,还是真的应该在StreamWriter周围使用using语句,以确保正确处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.