【问题标题】:Formatting a json with JsonResult Type in MVC在 MVC 中使用 JsonResult 类型格式化 json
【发布时间】:2020-01-17 00:18:00
【问题描述】:

我正在尝试创建一个 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": 部分?或者有没有更简单的方法来解决我错过的这个问题?

谢谢!

【问题讨论】:

    标签: c# asp.net-mvc slack-api jsonresult


    【解决方案1】:

    在您展示的 JSON 中,"blocks" 是根对象的一个​​属性。因此,您可以创建一个具有与之匹配的属性的包装类:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      相关资源
      最近更新 更多