Search code examples
c#jsonslack

How to serialize slack block? in C#


I made a template using Slack block kit builder

I read some data and fill eight parameters

in my C# code I have to use interpolated string and curly braces to supply the parameters {}. I also need to skip the braces by adding them twice.

but this is not recognized as correct json when I make the post message call :

var data = new NameValueCollection();
data["token"] = token;
data["channel"] = channelName;
data["as_user"] = "true";           
data["text"] = postedMessage;
data["blocks"]=jsonstring; 
var client = new WebClient();
var response = client.UploadValues("https://slack.co/api/chat.postMessage", "POST", data);
string responseInString = Encoding.UTF8.GetString(response);
Console.WriteLine(responseInString);

I understand the correct way is to represent these blocks as classes . I tried to follow the slack attachment representation but the blocks are more complex containing inner objects and not string variables as the attachment class . Appreciate your support to represent the blocks using easy syntax and correct json


Solution

  • The reason your code does not work is that in C# single quotes only work for single characters. Here is how to properly escape double quotes and curly brackets of a JSON for hard-coded string constants.

    normal string constants

    To properly escape the hard-coded JSON inside your code you need to add a backslash to each and every double quotes of your JSON string.

    Example:

    string someJson = "{\"ErrorMessage\": \"\",\"ErrorDetails\": {\"ErrorID\": 111,\"Description\":{\"Short\": 0,\"Verbose\": 20},\"ErrorDate\": \"\"}}";
    

    There are other ways on how to do it. See this question for a full overview of the solutions.

    Btw. you will not need to escape curly brackets in this approach.

    interpolated string constants

    With interpolated string you also need to escape the double quotes. But here it works by doubling them.

    Example:

    string someJson = "{\"ErrorMessage\": \"\",\"ErrorDetails\": {\"ErrorID\": 111,\"Description\":{\"Short\": 0,\"Verbose\": 20},\"ErrorDate\": \"\"}}";
    

    For interpolated strings you will also need to escape the curly brackets. This works by doubling the escaped curly brackets, since the single curly brackets are used for interpolating.

    Example:

    var json = $@"{{""name"":""{name}""}}";
    

    See also this answer for a full discussion on how to escape curly brackets.