【发布时间】:2018-05-25 16:52:02
【问题描述】:
我正在将数据表行转换为 JSON 字符串。使用 Javascript 序列化程序,我生成了一个普通的 JSON 字符串。我们如何将其生成为嵌套字符串。
当前 Json 输出
{
"PatientId":"32424",
"CustomerId":"XXXX",
"Name":"DiastolicBloodPressure",
"Value":89,
"Unit":"mmHg",
"MinValue":50,
"MaxValue":90,
"SessionElementResponseText":null
}
预期
{
"PatientId":"32424",
"CustomerId":"XXXX",
"VitalThreshold":{
"Name":"DiastolicBloodPressure",
"Value":89,
"Unit":"mmHg",
"MinValue":50,
"MaxValue":90
},
"SessionElementResponseText":null
}
代码
public static string DataTableToJSON(DataTable table)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach(DataRow dr in table.Rows)
{
row = new Dictionary<string, object>();
foreach(DataColumn col in table.Columns)
{
if(col.ColumnName.Equals("Name"))
{
//Trying here
}
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
serializer.MaxJsonLength = int.MaxValue;
return serializer.Serialize(rows);
}
【问题讨论】:
-
DataTable中的数据长得像什么?
-
@RawitasKrungkaew - 数据表看起来像上面的
Current Json output。数据表的列名是 PatientId |客户 ID |姓名 |价值 |单位 |最小值 |最大值 | SessionElementResponseText
标签: c# .net json datatable javascriptserializer