Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#?

like image 747
RBT Avatar asked Jun 16 '17 06:06

RBT


People also ask

How do you use string interpolation?

As the colon (":") has special meaning in an interpolation expression item, to use a conditional operator in an interpolation expression, enclose that expression in parentheses. string name = "Horace"; int age = 34; Console. WriteLine($"He asked, \"Is your name {name}?\

What is literal string interpolation?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

Why do we use string interpolation?

The string interpolation feature is built on top of the composite formatting feature and provides a more readable and convenient syntax to include formatted expression results in a result string.

What is a verbatim string literal and why do we use it?

Verbatim strings literals are often useful for embedding filenames and regular expressions in the source code, because backslashes in these types of strings are common and would need to be escaped if a regular string literal were used.


2 Answers

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;
}
like image 182
Richa Garg Avatar answered Oct 15 '22 21:10

Richa Garg


I agree with everyone else that building it from strings is a bad idea. I also understand that you don't want to include an extra dependency.

Here's a bit of code I wrote previously to convert a Dictionary to a JSON string. It's pretty basic, only accepts string types, and doesn't escape quote marks in any of the names/values, but that can be done fairly easily.

If you're trying to serialize a large JSON string from basic types, this is the way I'd recommend to do it. It'll help you stay sane.

private static string DictToJson(Dictionary<string, string> Dict)
{
    var json = new StringBuilder();

    foreach (var Key in Dict.Keys)
    {
        if (json.Length != 0)
            json = json.Append(",\n");

        json.AppendFormat("\"{0}\" : \"{1}\"", Key, Dict[Key]);
    }
    return "{" + json.ToString() + "}";
}
like image 34
Zac Faragher Avatar answered Oct 15 '22 23:10

Zac Faragher