How can I remove escape characters from my JSON ob

2019-06-22 05:32发布

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

2条回答
小情绪 Triste *
2楼-- · 2019-06-22 06:17

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

return Request.CreateResponse(HttpStatusCode.OK, JsonConvert.DeserializeObject(corr_str, new JsonSerializerSettings()));
查看更多
该账号已被封号
3楼-- · 2019-06-22 06:20

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.

查看更多
登录 后发表回答