Search code examples
c#stringvariables

How can I Serialize my class in json body?


i have this code string, i need serialize my class X, y try use concat with "+ +" but , dont work .. i use c# and nugget RestClient, and this forn not the optimum ty,

var body = @"{
" + "\n" +
        @"    ""CompanyDB"":""VARIABLE "",
" + "\n" +
        @"    ""UserName"":""VARIABLE "",
" + "\n" +
        @"    ""Password"":""VARIABLE ""
" + "\n" +
        @"}";

Solution

  • I would suggest building JSON using a JSON serializer, as it's much less error-prone.

    Using JSON.NET:

    var body = JsonConvert.SerializeObject(new {
        CompanyDB = "abc",
        UserName = "def",
        Password = "ghi"
    });
    

    If you need to have the response formatted with newlines for some reason, you can pass Formatting.Indented to SerializeObject as the second argument.

    Try it online

    Using System.Text.Json:

    var body = JsonSerializer.Serialize(new {
        CompanyDB = "abc",
        UserName = "def",
        Password = "ghi"
    });
    

    If you need to have the response formatted with newlines for some reason, you can pass new JsonSerializerOptions() { WriteIndented = true } to Serialize as the second argument.

    Try it online