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

妖精的绣舞 提交于 2019-12-10 14:34:31

问题


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


回答1:


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.




回答2:


Update your response string as you want then deserialize and return.

return Request.CreateResponse(HttpStatusCode.OK, JsonConvert.DeserializeObject(corr_str, new JsonSerializerSettings()));


来源:https://stackoverflow.com/questions/17323983/how-can-i-remove-escape-characters-from-my-json-object-being-displayed-in-fiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!