How can I remove escape characters from my JSON object being displayed in Fiddler

11,812

If you are using Web API, then you don't need to call JsonConvert.SerializeObject(). Change the return type of your method to your Model class (instead of string) and then simply return the model. Web API will serialize it for you.

Share:
11,812
beaumondo
Author by

beaumondo

Updated on June 08, 2022

Comments

  • beaumondo
    beaumondo almost 2 years

    I would like to serialize my C# object to a JSON object without the final text string including escape characters.

    The below method is being called through a RESTful design and returns the following JSON object when called through fiddler, however I would like to remove the backslashes so it includes only the double quotes and respects the JSON format.

    "{\"model\":\"Faslev\",\"platform\":\"ABC\",\"year\":2010,\"month\":\"June\", \"plant\":\"ONDH\",\"country\":\"Brazil\"}"

    public string GetModelBySerialNumber(string serialNumber)
    {
        var model = new Model();
        using (var connection = new SqlConnection(DBUtility.DbConnection))
        {
            try
            {                    
                SqlCommand myProcedure = new SqlCommand("myProcedure", connection);
                myProcedure.CommandType = CommandType.StoredProcedure;
                myProcedure.Parameters.Add("@SerialNumber", SqlDbType.NVarChar).Value = serialNumber;
                connection.Open();
                SqlDataReader dataReader = myProcedure.ExecuteReader();
                while (dataReader.Read())
                {
                    Func<int, string> GetString =  (int i) => dataReader.GetString(i);
                    Func<int, Int32> GetInteger = (int i) => dataReader.GetInt32(i);
                    model.ModelName = GetString(0);
                    model.Platform = GetString(1);
                    model.Year = GetInteger(2);
                    model.Month = GetString(3);
                    model.Plant = GetString(4);
                    model.Country = GetString(5);                                                
                }                    
            }
            catch (SqlException exception) {Trace.WriteLine("Error Trace " + exception.Message);}
            finally {connection.Close();}
        }
        return JsonConvert.SerializeObject(model);
    }
    

    If I use concatenation, like below, then the object displays correctly without the backslash, but I don't really want to do this as it seems to be an over-complicated way to write an object out.

    public string Ping()
    {
        return "{Message" + ":" + "PONG" + "}";
    }
    

    "{Message:PONG}"