简体   繁体   English

C#将字符串转换为JSON

[英]C# Converting string to JSON

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. 我正在尝试将C#POST到可以实现的JSON有效负载,但是我在理解如何用我自己的字符串替换示例字符串方面遇到困难。

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. 当我对StringContent使用“ {\\” text \\“:\\” Hello,World!\\“}”时,代码可以正常运行,但是如果我尝试用output_message字符串替换它,它将无法正常工作。 I am trying to work out how I convert my output_message to a format that JSON can recognize. 我正在尝试找出如何将output_message转换为JSON可以识别的格式。

    {
        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 我想用字符串替换“ {\\” text \\“:\\” Hello,World!\\“}”

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 要使用JavaScriptSerializer您必须添加对System.Web.Extensions.dll的引用

So for your problem, we create an anonymous object with a property text we pass the value Aoutput_message 因此,对于您的问题,我们创建一个带有属性文本的匿名对象,并传递值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 例子

To the best of my knowledge people are moving away from JavaScriptSerializer and towards Json.NET. 据我所知,人们正在从JavaScriptSerializer转向Json.NET。 It's even recommended in the documentation here 甚至在这里的文档中建议

The corresponding Json.NET code would look something like: 相应的Json.NET代码如下所示:

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. 要使用Json.NET,您需要安装Newtonsoft.Json nuget软件包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM