Search code examples
c#asp.net-mvcslack-apijsonresult

Formatting a json with JsonResult Type in MVC


I'm trying to create a Slack bot. I have to respond to Slack with a json, like so:

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

I'm using the JsonResult function. My code looks like this:

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);
}

My output does not look like how I want it to. This is what I get:

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

It looks like I almost have everything right, except for that "blocks": string right before everything else. I am very confused about how I can include that part.

How can I include the "blocks": part? Or is there an easier way to go about this that I'm missing?

Thanks!


Solution

  • In the JSON you've shown, "blocks" is a property on the root object. So you can just create a wrapper class that has a property to match that:

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

    And then use that object when you construct the data to be serialized:

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