c# - 将 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",
}
解决方案
您需要执行以下操作,该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>"
}
}
推荐阅读
- c++ - C++ `std::sort` 指针指向 2D 数据而不复制
- php - 如何在这段代码中很好地结合 php 和 html?
- c# - 无法使用 C# 使用 Office 365 凭据发送电子邮件
- javascript - 尝试从 TS 迁移 JS 时未创建文件
- python - 将字符串的文本文件(不是精确的 dict 格式)转换为具有元组键和浮点值的 dict?
- sql - 如何在没有最大值的情况下获得 SQL Server 上字段的最大值?
- ios - 如何在运行时获取 iOS 中所有可见的 UI 元素?
- java - 如何将 grpc 编码的数据存储在 Java 字符串中?
- c++ - 如何使用 cpp 设置随机数生成器的语法?
- google-aiy - 在哪里可以下载 mobilenet_v1_160res_0.5_imagenet_labels.txt 进行本地测试?