Search code examples
c#stringstring-interpolation

Request Body with String Interpoloation


I have a Post API that contains the following Request Body

{
      "format": "csv",
      "compress": "false",
      "startDate":"2023-07-25T00:00:00Z"
}

here is my code, my variable is returning correclty but i can't get the String Interpolation set up correctly please help!

var strStartDateZulu = strStartDate+"Z";
return await MakeApiCallAsync("RequestFileAsync", string.Empty, HttpMethod.Post, $"{\"format\":\"csv\", \"compress\":\"false\", \"startDate\":\"{strStartDateZulu}\"}", false);

Solution

  • Personally I would just use serialization with anonymous object, i.e. something like the following:

    var request = JsonSerializer.Serialize(new
    {
        format = "csv",
        compress = "false",
        startDate = strStartDateZulu
    });
    

    But if you are keen on using string interpolation you will need to use double curly braces to escape curly braces in the interpolated string:

    var request = $"{{\"format\":\"csv\", \"compress\":\"false\", \"startDate\":\"{strStartDateZulu}\"}}";
    

    Also since C# 11 you also can use raw string literals:

    var request = $$"""
    {
        "format":"csv",
        "compress": "false",
        "startDate": "{{strStartDateZulu}}"
    }             
    """;