数据读取器以JSON格式返回

时间:2017-12-15 03:43:16

标签: json sql-server database sqldatareader

这是我通过datareader返回数据的代码,但我希望它返回json输出而不是列结果。我应该更改它返回JSON myReader?

 if (key.Equals("1"))
        {
            Console.WriteLine("Enter Command to retrieve data");
            String sql = Console.ReadLine();
            if (String.IsNullOrEmpty(sql))
            {
                Console.WriteLine("invaild command");
                return;
            }
            try
            {
                SqlDataReader datareader = sh.ExecuteReader(sql, conn);
                if (datareader.Read())
                {
                    while (datareader.Read())
                    {
                        for (int index = 0; index < datareader.FieldCount; index++)
                        {
                            Console.WriteLine(datareader.GetValue(index));
                        }
                    }
                }
                else
                {
                    Console.WriteLine("unable to find the data");
                }
                datareader.Close();
            }

1 个答案:

答案 0 :(得分:0)

选择查询的

,最后添加FOR JSON PATH。喜欢这个

 SELECT TOP 2  
    SalesOrderNumber,  
    OrderDate,  
    (SELECT UnitPrice, OrderQty  
      FROM Sales.SalesOrderDetail AS D  
      WHERE H.SalesOrderID = D.SalesOrderID  
     FOR JSON PATH) AS D  
FROM Sales.SalesOrderHeader AS H  
FOR JSON PATH 

没有JSON PATH的结果

enter image description here

JSON PATH的结果

enter image description here

参见另一个例子

enter image description here

参考此MSDN Article for more details