Saturday 22 October 2022

Writing a json Easily and Elegently in in C# 11

 In the previous post "No More " Escaping Needed with C# 11" we have discussed, how the json can be writen in C# code, without having to escape each occurance of double quote, when we use the new C# 11 feature Raw String Literals. You might not want to hardcode the entire json in code, instead may want to use variables dynamically setting the json body content. Let's see how we can use String interpolation, in Raw String Leiterals to write json body elegently, and have variables dynamically set values in the josn.

For example lets take the "No More " Escaping Needed with C# 11" code below. 

// Print json file to console
Console.WriteLine("""
    {
        "name": "John",
        "age": 30,
        "cars": [
            "Ford",
            "BMW",
            "Fiat"
        ]
    }
    """);

Let's say we need to dynamically inject the name and age of current user to the json above. We can use string interpolation using a $ sign to add variables to strings. But what happens if we try to use a $ with the above sample code, you can see it errors out as below. Of course name and age varaibles can be used but, other single { and } usage woll give errors.


To fix the issue we can use $$ instead of one $ for string interpolation. That will require {{variablename}} syntax to inject variables in the string. That way we can keep the json required { and } characters as needed. 

// Get name of the current user
Console.WriteLine("What is your name?");
string? name = Console.ReadLine();

// Get age of the current user
Console.WriteLine("How old are you?");
int age = Convert.ToInt32(Console.ReadLine());

// Print json file to console
Console.WriteLine($$"""
    {
        "name": "{{name}}",
        "age": {{age}},
        "cars": [
            "Ford",
            "BMW",
            "Fiat"
        ]
    }
    """);

Now, when we run the app we can provide a name and an age and it will be used in the json.


If you use $$$ to inject the variable you need to use {{{variablename}}}. So it is number of { equal to number of $ used. So below syntax work exactly as shown in above output.

// Get name of the current user
Console.WriteLine("What is your name?");
string? name = Console.ReadLine();

// Get age of the current user
Console.WriteLine("How old are you?");
int age = Convert.ToInt32(Console.ReadLine());

// Print json file to console
Console.WriteLine($$$$"""
    {
        "name": "{{{{name}}}}",
        "age": {{{{age}}}},
        "cars": [
            "Ford",
            "BMW",
            "Fiat"
        ]
    }
    """);

No comments:

Popular Posts