3

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 \"
    }";
Frank Q.
  • 6,001
  • 11
  • 47
  • 62

3 Answers3

10

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.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
5

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 @.

Kenneth
  • 28,294
  • 6
  • 61
  • 84
2

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"
 }
Rahul
  • 76,197
  • 13
  • 71
  • 125