简体   繁体   中英

Adding string to verbatim string literal

I am trying to construct a raw json string as below to send it out in http request

var requestContent = @"{
                    ""name"": ""somename"",
                    ""address"": ""someaddress""
}";

Instead of having name and address value hardcoded I was hoping to supply them from below variables

string name = "someName";
string address = "someAddress";

But the below does not work. Any idea ?

var requestContent = @"{
                        ""name"": \" + name \",
                        ""address"": \" + address \"
    }";

The correct syntax is:

var requestContent = @"{
    ""name"": """ + name + @""",
    ""address"": """ + address + @"""
}";

Or, you could use string.Format :

var requestContent = string.Format(@"{
    ""name"": ""{0}"",
    ""address"": ""{1}""
}", name, address);

Or you could use an actual JSON serializer.

You could use a verbatim string together with interpolation as well:

var requestContent = $@"{{
    ""name"": ""{name}"",
    ""address"": ""{address}""
}}";

EDIT: For this to work you have to make sure that curly braces you want in the output are doubled up (just like the quotes). Also, first $ , then @ .

Instead use Newtonsoft.JSON JObject() like

dynamic myType = new JObject();
myType.name = "Elbow Grease";
myType.address = "someaddress";

Console.WriteLine(myType.ToString());

Will generate JSON string as

 {
  "name": "Elbow Grease",
  "address": "someaddress"
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM