Frank Q. Frank Q. - 3 months ago 36
JSON Question

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 \"
}";

Answer

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.