我正在尝试从Slack的HTTP POST请求返回一个json文件。我正在使用netcoreapp3.1和Newtonsoft.Json NuGet。现在我的HTTP POST函数看起来像这样。
public async Task<ActionResult> SlashCommand([FromForm] SlackSlashCommand request)
{
var retVal = new JsonResult(GetBlock());
return retVal;
}
GetBlock()是一个返回我创建的类的函数。目前可以使用,但是每次我想修改它返回的json时,都必须修改该类。我真的很想拥有一个字符串格式的json,可以将其复制并粘贴到我的代码中,然后以json格式返回到Slack。
有没有办法做到这一点?我一直在尝试使用JsonConvert.DeserializeObject(str);但是我使用不正确。据我了解,该函数接收一个字符串并将其转换为对象。我需要输入一个字符串并将其转换为Microsoft.AspNetCore.Mvc.ActionResult json。
有帮助吗?谢谢。
我找到了答案。
这是我的字符串格式的JSON:
string str = "{\"blocks\": [{\"type\": \"section\",\"text\": {\"type\": \"plain_text\",\"text\": \"Hello!\",\"emoji\": true}},{\"type\": \"divider\"},{\"type\": \"actions\",\"elements\": [{\"type\": \"button\",\"text\": {\"type\": \"plain_text\",\"text\": \"Help\"},\"value\": \"helpButton\"}]}]}";
然后这是我的功能:
public async Task<ActionResult> SlashCommand([FromForm] SlackSlashCommand request)
{
var retVal = new JsonResult(JsonConvert.DeserializeObject<object>(str));
return retVal;
}
效果很好。抱歉,如果我没有提供太多信息。
另一种选择是使用匿名类型,这种类型更不容易变成无效的JSON:
var data = new
{
blocks = new object[] {
new {
type = "section",
text = new {
type = "plain_text",
text = "Hello!",
emoji = true
}
},
new {
type = "divider"
},
new {
type = "actions",
elements = new object[] {
new {
type = "button",
text = new {
type = "plain_text",
text = "Help"
},
value = "helpButton"
}
}
}
}
};
return new JsonResult(data);
产品:
{
"blocks": [
{
"type": "section",
"text":
{
"type": "plain_text",
"text": "Hello!",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text":
{
"type": "plain_text",
"text": "help"
},
"value": "helpButton"
}
]
}
]
}