Friday 2 July 2021

Using variables in multiline Verbatim String in C#

Hi All,

I had a requirement to pass a json payload to HttpRequest. Json payload was expected to be dynamic in nature, so that it can be utilized for creating multiple HTTP requests.

It took me some time to figure out the answer so here I am writing this blog to help others like me.

Sample Json payload given below. Requirement was to pass variable to ServerName and to some other fields in the payload (I have not mentioned them all here to keep this example simple and neat)

string createTicketJson =
@"[
    {
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Title"",
        ""Value"": ""Server 1234: Shutdown Request""
    },
    {
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Description"",
        ""Value"": ""Please shutdown Server 1234. Ticket can be closed after completion of request.""
    },
    {
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Severity"",
        ""Value"": ""3""
    },
    {
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Requester"",
        ""Value"": ""Sonam""
    },
    {
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Notifications"",
        ""Value"": ""sonam@xyz.com""
    }
]";

A static Json payload will look like below. I have shown the payload in a MessageBox for readability purpose.

Solution

With C# 6, string interpolation can be used. So I added a $ sign in front of createTicketJson variable and replaced hardcoded value of Server Name ‘1234’ with variable serverName in curly brackets {serverName}.

This gave me a compilation error and I realized that my single curly bracket { is giving this error since it expects a single line value (variable) inside it.

To resolve this issue and treat curly bracket as text (instead of variable holder), it needs to be duplicated like below and TADA you have the dynamic version ready for json payload.

Final payload will look like below

string createTicketJson =
$@"[
    {{
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Title"",
        ""Value"": ""Server {serverName}: Shutdown Request""
    }},
    {{
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Description"",
        ""Value"": ""Please shutdown Server {serverName}. Ticket can be closed after completion of request.""
    }},
    {{
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Severity"",
        ""Value"": ""3""
    }},
    {{
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Requester"",
        ""Value"": ""Sonam""
    }},
    {{
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Notifications"",
        ""Value"": ""sonam@xyz.com""
    }}
]";

Hope this was helpful. Happy Coding!!!

No comments:

Post a Comment