伙计们,
我正在从插值字符串构建一个JSON对象,而不是获取转义的工作原理。我必须为API使用双引号。
这不会插入花括号之间的表达式:
@"{{
""name"":""{taskName}"",
""products"": [
{""product"": ""ndvi_image"", ""actions"": [""mapbox"", ""processed""]},
{""product"": ""true_color"", ""actions"": [""mapbox"", ""processed""]}
],
""recurring"":true,
""query"": {
""date_from"": ""{dateFromString}"",
""date_to"": ""{dateToString}"",
""aoi"": {polygon}
},
""aoi_coverage_percentage"":90
}}";
这引发了一堆错误 - 显然,大括号没有被正确转义:
$"{{
""name"":""{taskName}"",
""products"": [
{""product"": ""ndvi_image"", ""actions"": [""mapbox"", ""processed""]},
{""product"": ""true_color"", ""actions"": [""mapbox"", ""processed""]}
],
""recurring"":true,
""query"": {
""date_from"": ""{dateFromString}"",
""date_to"": ""{dateToString}"",
""aoi"": {polygon}
},
""aoi_coverage_percentage"":90
}}";
如何格式化它以保留内部双引号和外括号,同时允许插入单括号内的值?
答案 0 :(得分:14)
您似乎错过了products
和query
对象的转义:
$@"{{
""name"":""{taskName}"",
""products"": [
{{""product"": ""ndvi_image"", ""actions"": [""mapbox"", ""processed""]}},
{{""product"": ""true_color"", ""actions"": [""mapbox"", ""processed""]}}
],
""recurring"":true,
""query"": {{
""date_from"": ""{dateFromString}"",
""date_to"": ""{dateToString}"",
""aoi"": {polygon}
}},
""aoi_coverage_percentage"":90
}}";
答案 1 :(得分:11)
除了@"..."
和$"..."
C#支持$@"..."
字符串,这是您在构建需要插值的多行字符串文字时所要查找的内容:
$@"{{
""name"":""{taskName}"",
""products"": [
{{""product"": ""ndvi_image"", ""actions"": [""mapbox"", ""processed""]}},
{{""product"": ""true_color"", ""actions"": [""mapbox"", ""processed""]}}
],
""recurring"":true,
""query"": {{
""date_from"": ""{dateFromString}"",
""date_to"": ""{dateToString}"",
""aoi"": {polygon}
}},
""aoi_coverage_percentage"":90
}}";
答案 2 :(得分:0)
以防万一其他人正在考虑这样做,最好创建一个匿名类型并将其序列化为json,其原因有两个:
taskName
带有双引号怎么办?)以下使用json.net进行序列化。
var jsonObj = new {
name = taskName,
products = new[] {
new { product = "ndvi_image", actions = new [] { new { mapbox = "processed" } },
new { product = "true_color", actions = new [] { new { mapbox = "processed" } }
},
recurring = true,
query = new {
date_from = dateFromString,
date_to = dateToString,
aoi = polygon
},
aoi_coverage_percentage = 90
};
var jsonString = JsonConvert.SerializeObject(jsonObj);