在 MVC 中使用 JsonResult 类型格式化 json

Formatting a json with JsonResult Type in MVC

我正在尝试创建一个 Slack 机器人。我必须用 json 回复 Slack,就像这样:

{
    "blocks": [
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": "*It's 80 degrees right now.*"
            }
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": "Partly cloudy today and tomorrow"
            }
        }
    ]
}

我正在使用 JsonResult 函数。我的代码如下所示:

public class Block
{
    public string type { get; set; }
    public Text text { get; set; }
}
public class Text
{
    public string type { get; set; }
    public string text { get; set; }
}

private List<Block> GetBlock()  
{  
    var block = new List<Block>  
    {  
        new Block
        {  
            type = "section",  
            text = new Text
            {
                type = "mrkdwn",
                text = "*It's 80 degrees right now.*"
            } 
        },  
        new Block
        {
            type = "section",
            text = new Text
            {
                type = "mrkdwn",
                text = "Partly cloudy today and tomorrow"
            }
        },  
    };  

    return block;  
}  

// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
    var blocks = GetBlock();
    return new JsonResult(blocks);
}

我的输出看起来不像我想要的那样。这是我得到的:

[
    {"type":"section","text":{"type":"mrkdwn","text":"*It\u0027s 80 degrees right now.*"}},
    {"type":"section","text":{"type":"mrkdwn","text":"Partly cloudy today and tomorrow"}}
]

看起来我几乎什么都做对了,除了 "blocks": 字符串就在其他所有内容之前。我对如何包含该部分感到非常困惑。

如何包含 "blocks": 部分?还是有更简单的方法来解决我所缺少的问题?

谢谢!

在您显示的 JSON 中,"blocks" 是根对象上的 属性。所以你可以创建一个包装器 class,它有一个 属性 来匹配:

public class BlockWrapper
{
    public List<Block> blocks { get; set; }
}

然后在构造要序列化的数据时使用该对象:

private BlockWrapper GetBlock()
{
    var blockWrapper = new BlockWrapper
    {
        blocks = new List<Block>
        { ... }
    };
    return blockWrapper;
}