C# Asp.Net - Json AppendFormat 返回错误

问题描述

我目前正在开发一个程序,该程序应该将 sql 数据库中的信息以 json 格式 放入,以便用于 amCharts。我收到一个我无法修复的 System.Format.Exception 错误。我还在学习使用 C# Asp.Net。 这是我的代码

// Get the connection string
        string connStr = ConfigurationManager.ConnectionStrings["CRMMonitor_sql"].ConnectionString;
        using (sqlConnection conn = new sqlConnection(connStr))
        {
            // Establish the connection with the database
            conn.open();

            // Construct and execute sql query which would return the total amount for each year
            sqlCommand query = new sqlCommand(chartsql,conn);

            // Begin iterating through the result set
            sqlDataReader rst = query.ExecuteReader();

while (rst.Read())
{
   jsonStr.AppendFormat("{\"label\": \"{0}\",\"value\": \"{1}\"}",@rst[0].ToString(),@rst[1].ToString());

}

输出应如下所示:

"data": [{
    "label": "label1","value": 501
  },{
    "label": "label2","value": 301
  },{
    "label": "label3","value": 128
  }]

解决方法

请使用专门用于创建 JSON 输出的工具,例如 Newtonsoft.Json

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class MyService
{
    private void Example()
    {
        using (var command = db.Database.GetDbConnection().CreateCommand())
        {
            using (var rst = command.ExecuteReader())
            {
                do
                {
                    var columns = new List<string>();
                    for (int i = 0; i < rst.FieldCount; i++)
                    {
                        columns.Add(rst.GetName(i));
                    }

                    while (rst.Read())
                    {
                        // use JObject to generate the JSON on the fly
                        var jsonObject = new JObject();

                        for (int i = 0; i < columns.Count; i++)
                        {
                            string name = columns[i];
                            object value = rst.GetValue(i);
                            JToken jsonValue = JToken.FromObject(value);
                            jsonObject.Add(name,jsonValue);
                        }

                        // serialize the JObject to JSON output
                        string asJsonString = jsonObject.ToString();
                    }
                } while (rst.NextResult());
            }
        }
    }
}