1

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

Sunil Mathari
  • 822
  • 2
  • 11
  • 21

1 Answers1

2

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;

        }
  • 3
    I don't think you need to do that. WCF will handle the JSON conversion for you. Simply make the return type of the function DataTable. E.g. see here http://stackoverflow.com/questions/2086666/how-do-i-return-clean-json-from-a-wcf-service – mlinth Nov 03 '14 at 09:26
  • 2
    How we can do the same for XML ? – Sunil Mathari Nov 03 '14 at 10:41
  • 3
    Make the return type DataTable and configure the WCF to return XML. See my earlier comment - WCF does this all for you... – mlinth Nov 04 '14 at 08:15