krishna mohan
krishna mohan

Reputation: 39

how to remove backslash from the json data in c#

I want to get datatable data in the json data, but while I am converting I am getting data with backslash symbol. how to remove the backslash or how to generate json data without backslash.

output data

 "[{\"Date\":\"2020-03-27T00:00:00\",\"Units\":1035.0},{\"Date\":\"2020-03-26T00:00:00\",\"Units\":1137.0},{\"Date\":\"2020-03-25T00:00:00\",\"Units\":1283.0},{\"Date\":\"2020-03-24T00:00:00\",\"Units\":635.0}]"

code

using Newtonsoft.Json;

public string GetFanHoursReport(string fromdate, string todate)
{
    string jsondata = "";
    using (ColdStorageAppEntities entities = new ColdStorageAppEntities())
    {
        try
        {
            using (SqlConnection con = new SqlConnection(strcon_coldstorage))
            {
                con.Open();
                SqlCommand cmd_getlatest = new SqlCommand(@"SELECT * from RawData", con);
                SqlDataAdapter da_getlatest = new SqlDataAdapter(cmd_getlatest);
                DataTable dt_getlatest = new DataTable();
                da_getlatest.Fill(dt_getlatest);
                jsondata=DataTableToJSONWithJSONNet(dt_getlatest);
            }

            return jsondata;
        }
        catch (Exception)
        {
            return null;
        }
    }
}

convertion code -

public string DataTableToJSONWithJSONNet(DataTable table)
{
    string JSONString = string.Empty;
    JSONString = JsonConvert.SerializeObject(table);
    return JSONString;
}

screenshot

Upvotes: 0

Views: 523

Answers (1)

Isaiah
Isaiah

Reputation: 101

In my experience, the backslashes only appear when you're viewing the string in a debugger. If you were to write

Console.WriteLine(jsondata);

you can confirm whether the string contains the extra escape characters.

Upvotes: 2

Related Questions