Escape Quote in C# for javascript consumption

后端 未结 9 1249
天涯浪人
天涯浪人 2020-11-27 17:24

I have a ASP.Net web handler that returns results of a query in JSON format

public static String dt2JSON(DataTable dt)
{
    String s = \"{\\\"rows\\\":[\";
         


        
9条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 17:52

    I think you should rather look at the JavaScriptSerializer class. It's a lot more stable, and will correctly handle any kind of data or escape characters etc. Also, your code will look a lot cleaner.

    In your case your class can look like this:

    public static String dt2JSON(DataTable dt) {
        var rows = new List();
        foreach(DataRow row in dt.Rows)
        {
            var rowData = new Dictionary();
            foreach(DataColumn col in dt.Columns)
                rowData[col.ColumnName] = row[col];
            rows.Add(rowData);
        }
        var js = new JavaScriptSerializer();
        return js.Serialize(new { rows = rows });
    }
    
    
    

    This method will return a correctly serialized json string... For example, sth like this:

    {"rows":[{"id":1,"name":"hello"},{"id":2,"name":"bye"}]}
    

    Have fun! :)

    提交回复
    热议问题