我正在尝试构建一个原始的json
字符串,如下所示,以便在http请求中发送它
var requestContent = @"{
""name"": ""somename"",
""address"": ""someaddress""
}";
我没有硬编码的名称和地址值,而是希望从下面的变量中提供它们
string name = "someName";
string address = "someAddress";
但下面不起作用。有什么想法吗?
var requestContent = @"{
""name"": \" + name \",
""address"": \" + address \"
}";
答案 0 :(得分:6)
正确的语法是:
var requestContent = @"{
""name"": """ + name + @""",
""address"": """ + address + @"""
}";
或者,您可以使用string.Format
:
var requestContent = string.Format(@"{
""name"": ""{0}"",
""address"": ""{1}""
}", name, address);
或者您可以使用实际的JSON序列化程序。
答案 1 :(得分:3)
您也可以将逐字字符串与插值一起使用:
myApp.controller('myCtrl', ['$scope', '$http', '$defer', 'NgTableParams',
function($scope, $http, $defer, NgTableParams) {
$http.get('services/data/count').success(function(data) {
$scope.totalRows = data.rowCount;
});
// ...
getData: function(params) {
$http.get('/services/data/' + params.page() + '/' + params.count()) {
.success(function(data) {
$scope.data = data;
$defer.resolve(data);
});
}
编辑:为此,你必须确保输出中你想要的花括号加倍(就像引号一样)。此外,首先是var requestContent = $@"{{
""name"": ""{name}"",
""address"": ""{address}""
}}";
,然后是$
。
答案 2 :(得分:2)
而是使用Newtonsoft.JSON JObject()
之类的
dynamic myType = new JObject();
myType.name = "Elbow Grease";
myType.address = "someaddress";
Console.WriteLine(myType.ToString());
将生成JSON字符串为
{
"name": "Elbow Grease",
"address": "someaddress"
}