Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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}"

like image 920
beaumondo Avatar asked Jun 26 '13 15:06

beaumondo


1 Answers

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.

like image 145
Brian Rogers Avatar answered Oct 08 '22 13:10

Brian Rogers