首页 > 解决方案 > 将 JSON 转换为 C#

问题描述

我正在尝试让我用 C# 编写的程序通过 Slack 应用程序发布到 Slack 频道,但使用此处建议的格式:https ://api.slack.com/tools/block-kit-builder

我在下面有这个代码,它发布到 Slack 频道,所以我知道这是有效的。

    {
        static void Main(string[] args)
        {
            PostWebHookAsync();
            Console.ReadLine();
        }
            static async void PostWebHookAsync()
            {
                using (var httpClient = new HttpClient())
                {
                    using (var request = new HttpRequestMessage(new HttpMethod("POST"), "my-webhook-link"))
                    {         
                    string jsonValue = JsonConvert.SerializeObject(new
                    {
                        type = "section",
                        text = "Some text \n new line \t tab",
                    }
                    );
                    Console.WriteLine(jsonValue);
                    Type valueType = jsonValue.GetType();
                    if (valueType.IsArray)
                    {
                        jsonValue = jsonValue.ToString();
                        Console.WriteLine("Array Found");
                    }                   
                    request.Content = new StringContent(jsonValue, Encoding.UTF8, "application/json");
                    var response = await httpClient.SendAsync(request);
                    Console.WriteLine(response.StatusCode);
                    Console.WriteLine(response.Content);
                    }
                }
            }
        }

返回:

{"type":"section","text":"Some text \n new line \t tab"}

现在我想发布这个

    {
        "type": "section",
        "text": {
            "type": "mrkdwn",
            "text": "This is a mrkdwn section block :ghost: *this is bold*, and ~this is crossed out~, and <https://google.com|this is a link>"
        }
    }

但是我很难理解要更改此代码块的目的

string jsonValue = JsonConvert.SerializeObject(new
                    {
                        type = "section",
                        text = "Some text \n new line \t tab",
                    }

标签: c#json

解决方案


您需要执行以下操作,该text属性是一个对象,因此只需创建另一个匿名对象。

string jsonValue = JsonConvert.SerializeObject(new
                    {
                        type = "section",
                        text = new 
                        {
                            type = "mrkdwn",
                            text = "This is a mrkdwn section block :ghost: *this is bold*, and ~this is crossed out~, and <https://google.com|this is a link>"
                        }
                    }

推荐阅读