How to Wrap dynamic string variables in double quoutes

Advertisements

I have static body which works great. But how I can wrap the same dynamic strings with double quotes – >""

Static Body

     var body = @"{" + "\n" +
        @"  ""profile"": {" + "\n" +
        @"    ""firstName"": ""Isaac1""," + "\n" +
        @"    ""lastName"": ""Brock1""," + "\n" +
        @"    ""email"": ""isaac1.brock@example.com""," + "\n" +
        @"    ""login"": ""isaac1.brock@example.com""," + "\n" +
        @"    ""mobilePhone"": ""555-415-1337""" + "\n" +
        @"  }" + "\n" +
        @"}";

Dyanmic Content (FirstName, LastName, Email, MobilePhone should all be wrapped with "")

var body1 = @"{" + "\n" +
                        @"  ""profile"": {" + "\n" +
                        @"    ""firstName"": "+ firstName + "," + "\n" +
                        @"    ""lastName"": "+lastName+"," + "\n" +
                        @"    ""email"": "+email+"," + "\n" +
                        @"    ""login"": "+email+"," + "\n" +
                        @"    ""mobilePhone"": "+mobilePhone+"" + "\n" +
                        @"  }" + "\n" +
                        @"}";

>Solution :

you can wrap a variable using string escape syntax " \ ""

var body1 = @"{" + "\n" +
                        @"  ""profile"": {" + "\n" +
                        @"    ""firstName"": " + "\"" + firstName + "\"" + "," + "\n" +
                        @"    ""lastName"": " + "\"" + lastName + "\"" + "," + "\n" +
                        //..... 
                        @"  }" + "\n" +
                        @"}";

but IMHO it is more safe to create a json object and after this to serialize it to a json string , using Newtonsoft.Json for example

var body = new JObject {
      ["profile"]=new JObject {
      ["firstName"] = firstName,
      ["lastName"] = lastName
      //...
    }
    }.ToString();

or you can replace JObject with an anonymos class and serialize after creaing.

Leave a ReplyCancel reply