18

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

RBT
  • 24,161
  • 21
  • 159
  • 240
  • 2
    Verbatim strings require that you escape double quotes by doubling them up. `$@"[{{""Key"":""{abc}"",""Value"": {pqr} }}]"` will work, but this is hardly more readable. Consider using a JSON serializer to avoid string wetwork. – Jeroen Mostert Jun 16 '17 at 06:52
  • 1
    @RBT even assuming you really really don't want to use a JSON serializer I'd avoid to build string this way, format string quickly becomes absolutely unreadable and error-prone. In this case maybe `String.Format()` will help and if you write few more functions then you will have a nice short readable code snippet (`QuoteJsonString()`, `ConvertToJsonKeyValuePair()` and one line LINQ to concat them...) – Adriano Repetti Jun 16 '17 at 06:57

3 Answers3

15

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;
}
RBT
  • 24,161
  • 21
  • 159
  • 240
Richa Garg
  • 1,888
  • 12
  • 23
  • 7
    This is not valid JSON. Single quotes are valid Javascript, but not JSON. – Pete Montgomery Jan 11 '19 at 11:23
  • You can use double quotes to escape the quotes, ie @" { ""key"": ""value"" } " However, despite the manual indicating that you can combine $@ for an interpolated verbatim string, VSCode is telling me that doing so is an error. Not sure what the exactly correct syntax is to achieve it. – Eric Blade Aug 26 '19 at 20:47
2

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() + "}";
}
Zac Faragher
  • 963
  • 13
  • 26
  • In my JSON data I can also have int, date values. You are taking every value as string. – RBT Jun 30 '17 at 14:01
1

you can create dictionary and serialize it to json using Json.NET does this.

Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");

string json = JsonConvert.SerializeObject(values);
// {
//   "key1": "value1",
//   "key2": "value2"
// }

you can see here more detail : http://www.newtonsoft.com/json/help/html/SerializingCollections.htm

Shyam sundar shah
  • 2,473
  • 1
  • 25
  • 40
  • I'm going to leverage this piece of code in a method which gets called from custom action of installshield. Adding a dependency on JSON.NET dll in my C# project will invite adding a dependency on this dll in the installshield project as well. This is an explicit work which is a fair amount of overhead just to fix this one line of code on C# side if at all it can be fixed. – RBT Jun 16 '17 at 07:00