如何解决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());
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。