Search code examples
c#wcfwcf-data-services

How to convert datatable to json string output using json.net WCF Rest Service


How to convert datatable to json string using json.net WCF Rest Service in c# WCF Application


Solution

  • U should use JsonConvert.SerializeObject followed by the datatable in the first parameter, and then the way you want to format it in the 2nd parameter.

    string json = JsonConvert.SerializeObject(objAcctDTable, Formatting.None);
    

    -edit-

    if you are struggling with the escape quotes or slashes, you should put your string through this function before doing anything with it

    public string EscapeQuotesMySql(string str)
            {
    
                string retVal = System.String.Empty;
    
                if (!System.String.IsNullOrEmpty(str))
                {
    
                    // replace special quotes
    
                    retVal = str.Replace((char)8216, '\'');
    
                    retVal = retVal.Replace((char)8217, '\'');
    
                    // escapes for SQL
    
                    retVal = retVal.Replace(@"\", @"\\");
    
                    retVal = retVal.Replace(@"'", @"\'");
    
                }
    
                return retVal;
    
            }