如何从C#数据表向json字符串中添加自定义的Key,values
本文关键字:自定义 添加 Key values 字符串 数据表 json | 更新日期: 2023-09-27 17:58:34
我的预期输出是:
{
key: "user",
values: [
{
"label" : "A" ,
"value" : 29.765957771107
} ,
{
"label" : "B" ,
"value" : 0
} ,
{
"label" : "C" ,
"value" : 32.807804682612
} ,
{
"label" : "D" ,
"value" : 196.45946739256
} ,
{
"label" : "E" ,
"value" : 0.19434030906893
} ,
{
"label" : "F" ,
"value" : 98.079782601442
} ,
{
"label" : "G" ,
"value" : 13.925743130903
} ,
{
"label" : "H" ,
"value" : 5.1387322875705
}
]
}
但是我得到的是
{
"user":[
{
"label":"122",
"value":"387"
},
{
"label":"136",
"value":"402"
},
{
"label":"59T",
"value":"34372"
},
{
"label":"601",
"value":"2970"
},
{
"label":"APA",
"value":"1"
},
{
"label":"B01",
"value":"3376"
},
{
"label":"B11",
"value":"5490"
},
{
"label":"C67",
"value":"5629"
},
{
"label":"CCS",
"value":"1671"
},
{
"label":"F31",
"value":"12"
},
{
"label":"F32",
"value":"4459"
},
{
"label":"FC0",
"value":"18780"
},
{
"label":"FMD",
"value":"15235"
},
{
"label":"GLC",
"value":"3202"
},
{
"label":"GRZ",
"value":"336"
},
{
"label":"HAM",
"value":"651"
},
{
"label":"OP1",
"value":"12771"
},
{
"label":"OP2",
"value":"2065"
},
{
"label":"OP3",
"value":"1519"
},
{
"label":"OZW",
"value":"2866"
},
{
"label":"RAO",
"value":"2907"
},
{
"label":"S00",
"value":"17467"
},
{
"label":"SIN",
"value":"13898"
},
{
"label":"SLE",
"value":"2549"
},
{
"label":"STR",
"value":"542"
},
{
"label":"TCG",
"value":"3628"
},
{
"label":"TCK",
"value":"1487"
},
{
"label":"TCM",
"value":"4729"
},
{
"label":"TCW",
"value":"6348"
},
{
"label":"TSS",
"value":"1543"
},
{
"label":"VA1",
"value":"1139"
},
{
"label":"VA2",
"value":"2370"
},
{
"label":"VA6",
"value":"1556"
},
{
"label":"YC1",
"value":"443"
},
{
"label":"YC2",
"value":"37"
},
{
"label":"YC4",
"value":"1"
},
{
"label":"YC6",
"value":"1"
},
{
"label":"YMW",
"value":"36"
}
]
}
我的c#类如下:
public class Propm2345
{
public string label { get; set; }
public string value { get; set; }
}
List<Propm2345> p911 = new List<Propm2345> { };
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public string get_OPC_Site_view()
{
string sit = "S00";
//select label, value from getOPC_site_count_for_chart
string query = "select label, value from getOPC_site_count_for_chart";
SqlCommand cmd = new SqlCommand(query);
DataSet ds = GetSITData1(cmd);
DataTable dt = ds.Tables[0];
foreach (DataRow item in ds.Tables[0].Rows)
{
Propm2345 pp = new Propm2345();
pp.label = item["label"].ToString();
pp.value = item["value"].ToString();
p911.Add(pp);
}
JavaScriptSerializer jss = new JavaScriptSerializer();
var obj = new { user = p911 };
string ss = jss.Serialize(obj);
return ss;
}
使用上面的代码,我得到了正确的输出,但我想添加自定义根键和值jsut来馈送nvd3图表。请帮助实现预期的json输出。
您必须以这种方式创建用于序列化的对象
JavaScriptSerializer jss = new JavaScriptSerializer();
var obj = new { key = "user", values = p911 };
string ss = jss.Serialize(obj);
return ss;