Search code examples
c#jsonhttpwebrequestsymbols

Passing symbols inside Json through HttpWebRequest


I try to pass message to MS Flow in Json format, using following method, but once I pass any symbols (like ") I get an error as symbols are recognized as code.

public static bool notification(string customer, string comment)
    {
        try
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("my msflow link goes here");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{ \"customer\":\"" + customer + "\",\"comment\":\"" + comment + "\"}";

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();

            }

            return true;
        }
        catch (Exception)
        {
            return false;
        }

    }

Solution

  • Try to use the JSON.NET to serialize your objekt in the code like this:

    string json = JsonConvert.SerializeObject(<your object>);