C# string interpolation-escaping double quotes and curly braces
It seems that you have missed escape for the products
and query
objects:
$@"{{
""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
}}";
Just in case someone else is considering doing the same, it would be better to create an anonymous type and serialize it to json for two reasons:
- it's a lot more readable and maintainable (how long would it take someone to change the code because the json structure has changed while keeping all escapes in order -- especially if there are no unit tests?)
- it's a lot more reliable (what if
taskName
has a double quote?)
Below uses json.net for serialization.
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);
In addition to @"..."
and $"..."
C# supports $@"..."
strings, which is what you are looking for when you build multi-line string literals that need to be interpolated:
$@"{{
""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
}}";