0

I am trying to POST to using C# to a JSON payload which I can achieve but I am having trouble understanding how to replace the sample string with my own string.

From the code below you can see I have a string I want to send to my weblink. The code runs fine when I use "{\"text\":\"Hello, World!\"}" for the StringContent but if I try to replace it with the string of output_message it doesn't work. I am trying to work out how I convert my output_message to a format that JSON can recognize.

    {
        string output_message = "The file " + filename + " has been modified by " + user_modified + " and moved to the " + file_state + " file state. Please review the " + filename + " file and approve or reject.";            
        PostWebHookAsync(output_message);
        Console.ReadLine();
    }
    static async void PostWebHookAsync(string Aoutput_message)
    {
        using (var httpClient = new HttpClient())
        {
            using (var request = new HttpRequestMessage(new HttpMethod("POST"), "www.mywebsitelink"))
            {
                //request.Content = new StringContent("{\"text\":\"Hello, World!\"}", Encoding.UTF8, "application/json");  // - original do not delete
                request.Content = new StringContent(Aoutput_message, Encoding.UTF8, "application/json");
                var response = await httpClient.SendAsync(request);
               Console.WriteLine(response.StatusCode);
               Console.WriteLine(response.Content);
            }
        }
    }

I want to replace "{\"text\":\"Hello, World!\"}" with a string

AWH
  • 9
  • 1
  • JSON is stand for JavaScript **Object** Notation, so it has some validation rules. In your case, you can send `$"\{\"text\":\"{output_message}\"\}"` or `$"\{\"value\":\"{output_message}\"\}"`, or even `$"[\"{output_message}\"]"` – vasily.sib May 13 '19 at 10:48
  • Possible duplicate of [Convert JSON String To C# Object](https://stackoverflow.com/questions/4611031/convert-json-string-to-c-sharp-object) –  May 13 '19 at 10:49

2 Answers2

1

The best way is to create an object and serialize it.

To use JavaScriptSerializer you have to add a reference to System.Web.Extensions.dll

So for your problem, we create an anonymous object with a property text we pass the value Aoutput_message

static async void PostWebHookAsync(string Aoutput_message)
{
    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(new HttpMethod("POST"), "www.mywebsitelink"))
        {
            //request.Content = new StringContent("{\"text\":\"Hello, World!\"}", Encoding.UTF8, "application/json");  // - original do not delete

            string jsonValue = new JavaScriptSerializer().Serialize(new
            {
                text = Aoutput_message,
            });

            request.Content = new StringContent(jsonValue, Encoding.UTF8, "application/json");
            var response = await httpClient.SendAsync(request);
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Content);
        }
    }
}

Examples

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
1

To the best of my knowledge people are moving away from JavaScriptSerializer and towards Json.NET. It's even recommended in the documentation here

The corresponding Json.NET code would look something like:

static async void PostWebHookAsync(string output_message)
{
    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(new HttpMethod("POST"), "www.mywebsitelink"))
        {
            string jsonValue = JsonConvert.SerializeObject(new
            {
                text = output_message
            });
            request.Content = new StringContent(jsonValue, Encoding.UTF8, "application/json");
            var response = await httpClient.SendAsync(request);
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Content);
        }
    }
}

To use Json.NET you need to install the Newtonsoft.Json nuget package.

Palle Due
  • 5,929
  • 4
  • 17
  • 32
  • This also work, thanks for your feedback. Whats the benefits of using this over the JavaScriptSerializer().Serialize function? – AWH May 13 '19 at 14:00
  • @AWH: JavaScriptSerializer is not supported in .NET Core, so in order to make it "future-proof" you should use Json.NET. When deserializing I find Json.NET easier to work with, for serialization it's same-same. – Palle Due May 13 '19 at 14:25