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但是不知道从哪里开始....

推荐答案

string json = JsonConvert.SerializeObject(table, Formatting.Indented);

编辑:当然,您不需要缩进格式,但它使其更美观、更具可读性.

Json相关问答推荐

使用Powershell脚本将配置信息块添加到json文件

Jolt转换,如果任何字段为空,则将对象值设置为空

您可以使用Jolt对JSON执行OR条件吗

使用WSO2 JsonTransform Mediator对空值执行JsonExceptionUndeletedOperationException

Bash和echo命令出现意外结果

Vegalite中分组条形图中的偏移量问题

NiFi QueryRecord处理器- Select 可选的JSON属性

导致此 Kotlin Retrofit2 错误的可能原因有哪些?

Oracle JSON 查询中的动态列列表

将请求中的数据推送到数组中

jolt 通配符如何用于 RHS?

使用 Jolt 变换将平面 json 转换为具有多个数组的嵌套 Json

Golang / Go - 如果 struct 没有字段,如何将其编组为空?

如何比较 JSON 文档并返回与 Jackson 或 Gson 的差异?

如何在返回对象的 Spring MVC @RestController @ResponseBody 类中响应 HTTP 状态代码?

十六进制格式可以与 JSON 文件一起使用吗?如果是这样,怎么做?

通过 RestAssured 中的 JsonPath 访问匿名数组的元素

从 JSON 中 Select 不同的值

为什么 jqXHR.responseText 返回字符串而不是 JSON 对象?

JSON键是否需要唯一?