3

我正在尝试构建json如下的原始字符串以在 http 请求中发送它

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

我希望从下面的变量中提供它们,而不是硬编码名称和地址值

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

但以下不起作用。任何想法 ?

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

3 回答 3

9

正确的语法是:

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

或者,您可以使用string.Format

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

或者您可以使用实际的 JSON 序列化程序。

于 2016-08-24T22:36:17.447 回答
5

您也可以将逐字字符串与插值一起使用:

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

编辑:为此,您必须确保输出中所需的花括号加倍(就像引号一样)。还有,先$,然后@

于 2016-08-24T22:40:31.830 回答
2

而是使用Newtonsoft.JSON JObject()like

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

Console.WriteLine(myType.ToString());

将生成 JSON 字符串为

 {
  "name": "Elbow Grease",
  "address": "someaddress"
 }
于 2016-08-24T22:37:29.820 回答