Search code examples
c#json.netstring-interpolationverbatim-string

How to use string interpolation and verbatim string together to create a JSON string literal?


I'm trying to create a string literal representing an array of JSON objects so I thought of using string interpolation feature as shown in the code below:

    public static void MyMethod(string abc, int pqr)
    {
        string p = $"[{{\"Key\":\"{abc}\",\"Value\": {pqr}  }}]";
    }

Now I thought of using verbatim string so that I don't have to escape double quotes using backslashes. So I came to know through this answer that verbatim string and string interpolation can be used together. So I changed my code as below:

public static void MyMethod(string abc, int pqr)
{
    string p = $@"[{{"Key":"{abc}","Value": {pqr} }}]";
}

But it fails to compile. Can anyone help me if there is anything wrong in my usage or it will not be possible to escape double quotes in such a case using string verbatim feature of C#?


Solution

  • The best way is to use JSON serializers as they have in-built handling related to escape characters and other things. See here.

    However, if we want to go through this path only to create the JSON string manually, then it can be solved as follows by changing the inner double quotes to single quotes :

    public static string MyMethod(string abc, int pqr)
    {
       string p = $@"[{{'Key':'{ abc}','Value': {pqr} }}]";
       return p;
    }