仅使用Value将DataTable转换为JSON [英] Convert DataTable to JSON with only Value
本文介绍了仅使用Value将DataTable转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
f我有以下结构的数据表。
f I have a datatable in the following structure.
HostelName FloorName FlatName Occupied Vacant
Building One Floor A A 2 2
Building One Floor A B 0 4
Building One Floor A C 0 4
Building One Floor A D 0 4
Building One Floor A E 0 4
Building One Floor B F 0 4
Building One Floor B G 0 4
Building One Floor B H 0 4
Building One Floor B I 0 4
Building One Floor B J 0 4
I would like to serialize it as a JSON object where the HostelName,FloorName & FlatName columns are the nodes in the JSON object like:
{
"Building One": {
"Floor A": {
"A": {
"Occupied": "2",
"Vacant": "2"
},
"B": {
"Occupied": "0",
"Vacant": "4"
},
"C": {
"Occupied": "0",
"Vacant": "4"
},
"D": {
"Occupied": "0",
"Vacant": "4"
},
"E": {
"Occupied": "0",
"Vacant": "4"
}
},
"Floor B": {
"F": {
"Occupied": "0",
"Vacant": "4"
},
"G": {
"Occupied": "0",
"Vacant": "4"
},
"H": {
"Occupied": "0",
"Vacant": "4"
},
"D": {
"Occupied": "0",
"Vacant": "4"
},
"I": {
"Occupied": "0",
"Vacant": "4"
}
}
}
};
请帮我解决。
谢谢
Subin ks
Please help me to solve it.
Thank you
Subin ks
推荐答案
请参阅: http://stackoverflow.com/a/11182071 [ ^ ]。它不完全是你想要的。你需要做一些修改。
问候..
See this : http://stackoverflow.com/a/11182071[^]. Its not exactly what you are looking for. You need some modifications.
Regards..
int i = 0;
StringBuilder sbJSON = new StringBuilder();
datatable dt;
sbJSON.Append([);
if(dt.Rows.count> 0)
{
foreach(DataRow dr in dt.Rows)
{
sbJSON.Append( {\+ dr [0] +\:);
sbJSON.Append(,\+ dr [1] +\:) ;
sbJSON.Append(,\+ dr [2] +\:);
sbJSON.Append(\ + dr [3] +\,);
sbJSON.Append(\+ dr [4] +\},);
}
sbJSON.Remove(sbJSON.Length - 1,1);
}
sbJSON.Append(] );
result = sbJSON.ToString();
int i=0;
StringBuilder sbJSON = new StringBuilder();
datatable dt;
sbJSON.Append("[");
if(dt.Rows.count>0)
{
foreach (DataRow dr in dt.Rows)
{
sbJSON.Append("{\"" + dr[0] + "\": ");
sbJSON.Append(",\"" + dr[1] + "\": ");
sbJSON.Append(",\"" + dr[2] + "\": ");
sbJSON.Append("\"" + dr[3] + "\",");
sbJSON.Append("\"" + dr[4] + "\"},");
}
sbJSON.Remove(sbJSON.Length - 1, 1);
}
sbJSON.Append("]");
result = sbJSON.ToString();
这篇关于仅使用Value将DataTable转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文