如何使用 json.net 将数据表转换为 json 字符串? [英] How to convert datatable to json string using json.net?
本文介绍了如何使用 json.net 将数据表转换为 json 字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 json.net 将数据表转换为 json?任何建议......我已经下载了必要的二进制文件......我应该使用哪个类来将我的数据表转换为json?到目前为止,使用此方法通过传递我的数据表来获取 json 字符串...
How to convert datatable to json using json.net? Any suggestion... I ve downloaded the necessary binaries... Which class should i use to get the conversion of my datatable to json? Thus far used this method to get json string by passing my datatable...
public string GetJSONString(DataTable table)
{
StringBuilder headStrBuilder = new StringBuilder(table.Columns.Count * 5); //pre-allocate some space, default is 16 bytes
for (int i = 0; i < table.Columns.Count; i++)
{
headStrBuilder.AppendFormat(""{0}" : "{0}{1}¾",", table.Columns[i].Caption, i);
}
headStrBuilder.Remove(headStrBuilder.Length - 1, 1); // trim away last ,
StringBuilder sb = new StringBuilder(table.Rows.Count * 5); //pre-allocate some space
sb.Append("{"");
sb.Append(table.TableName);
sb.Append("" : [");
for (int i = 0; i < table.Rows.Count; i++)
{
string tempStr = headStrBuilder.ToString();
sb.Append("{");
for (int j = 0; j < table.Columns.Count; j++)
{
table.Rows[i][j] = table.Rows[i][j].ToString().Replace("'", "");
tempStr = tempStr.Replace(table.Columns[j] + j.ToString() + "¾", table.Rows[i][j].ToString());
}
sb.Append(tempStr + "},");
}
sb.Remove(sb.Length - 1, 1); // trim last ,
sb.Append("]}");
return sb.ToString();
}
现在我想使用 json.net 但不知道从哪里开始....
Now i thought of using json.net but dont know where to get started....
推荐答案
string json = JsonConvert.SerializeObject(table, Formatting.Indented);
当然,您不需要缩进格式,但它使其美观且可读.
You don't need indented formatting, of course, but it makes it nice and readable.
这篇关于如何使用 json.net 将数据表转换为 json 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文