简体   繁体   中英

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. The JSON being formed is relatively large. However when I am trying to read the JSON from C# the JSON is not appearing properly. C# code below to read the JSON from SQL Server

   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:

"Det":[{"id":3700159,"address":"601   Union St  Seattle, WA 98

As you can see the JSON did not end properly. Any idea why this is happening?

Use a using statement on your file. 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. You could do that with file.AutoFlush = true; or with 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM