The immediate problem is that you've got two string literals: a verbatim string literal at the start, and then a regular string literal after the string concatenation with amnt
. To make it simpler to see, you've got:
string text = @"some text
more text" + amnt + "more text
more text";
That second string literal is a regular string literal, which means it can't go over multiple lines. That's why you're getting an error at the moment.
That's not the only problem you've got though:
- The JSON you're producing at the moment is invalid anyway, as all of these single quotes should be double quotes. While several JSON parsers will allow single quotes, this does violate RFC 7159
- Putting everything in string literals is a very brittle way of producing JSON. It's very easy to make a small typo and end up with invalid JSON.
There are several options here:
- You could use a verbatim interpolated string literal, allowing you to write a single literal with
{amnt}
to include the value there. The disadvantage is that you'd need to double all the braces to indicate that you wanted actual braces
- You could make the second string literal a verbatim string literal, by adding
@
at the start of it
- You could avoid doing all of this in strings to start with and use a JSON library to produce the JSON.
I'd definitely take the last option - I'd use Json.NET.
There are lots of ways of doing this in Json.NET. For example:
- You could model the JSON object in regular classes, and serialize instances of those classes. If you need this JSON more than once, that's what I'd do. That would let you use idiomatic C# names for properties, using attributes to specify how those properties should be represented in JSON.
- You could use LINQ to JSON to create
JObject
and JArray
instances.
- You could use an anonymous type.
Here's an example of the latter approach:
using System;
using Newtonsoft.Json;
class Test
{
public static void Main()
{
string amount = "1000000";
var obj = new
{
method = "submit",
// Note: @ is required as params is a keyword
@params = new[]
{
new
{
secret = "snL7AcZbKsHm1H7VjeZg7gNS55Xkd",
tx_json = new
{
Account = "rHSqhmuevNJg9ZYpspYHNnQDxraozuCk5p",
TransactionType = "PaymentChannelCreate",
Amount = amount,
Destination = "rD6CGd2uL9DZUVDNghMqAfr8doTzKbEtGA",
SettleDelay = 86400,
PublicKey = "023693F15967AE357D0327974AD46FE3C127113B1110D6044FD41E723689F81CC6",
DestinationTag = 20170428
},
fee_mult_max = 1000
}
}
};
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
Console.WriteLine(json);
}
}
Output:
{
"method": "submit",
"params": [
{
"secret": "snL7AcZbKsHm1H7VjeZg7gNS55Xkd",
"tx_json": {
"Account": "rHSqhmuevNJg9ZYpspYHNnQDxraozuCk5p",
"TransactionType": "PaymentChannelCreate",
"Amount": "1000000",
"Destination": "rD6CGd2uL9DZUVDNghMqAfr8doTzKbEtGA",
"SettleDelay": 86400,
"PublicKey": "023693F15967AE357D0327974AD46FE3C127113B1110D6044FD41E723689F81CC6",
"DestinationTag": 20170428
},
"fee_mult_max": 1000
}
]
}