C#多行多双引号字符串
Posted
技术标签:
【中文标题】C#多行多双引号字符串【英文标题】:C# Multiline multi-double quote string 【发布时间】:2021-08-27 22:37:33 【问题描述】:我需要做这样的文字:
"method": "api.notifications.add",
"params":
"name": "sequence.state.changed",
"options":
"include_print_record": true,
"include_layout": true
,
"id": 0,
"jsonrpc": "2.0"
用c#变成一个字符串比如这样:
input = @"
"method": "api.notifications.add",
"params":
"name": "sequence.state.changed",
"options":
"include_print_record": true,
"include_layout": true
,
"id": 0,
"jsonrpc": "2.0"
";
它需要保留它拥有的格式。我已经尝试了很多方法,包括在每个引号之前添加一个反斜杠,并且显然在第一个引号之前添加一个 @ 符号。
【问题讨论】:
看起来您正在尝试使用强连接生成 JSON。不要那样做。创建类,然后序列化为 JSON。 【参考方案1】:根据您的口味类型,我喜欢使用反斜杠。
string input =
"\"method\": \"api.notifications.add\"," +
"\"params\": " +
"\"name\": \"sequence.state.changed\"," +
"\"options\": " +
"\"include_print_record\": true,\"" +
"include_layout\": true" +
"," +
"\"id\": 0," +
"\"jsonrpc\": \"2.0\"" +
"";
然而,正如上面在 cmets 中提到的,你最好创建一个 Class 或 Struct 然后序列化 json 数据。这似乎需要做很多工作,但你从长远来看,我会感谢你自己。这是一个可以帮助你入门的简单示例。
namespace Foo
public class MyInputObject
[JsonPropertyName("method")]
public string Method get; set;
[JsonPropertyName("params")]
public Params Params get; set;
[JsonPropertyName("id")]
public long Id get; set;
[JsonPropertyName("jsonrpc")]
public string Jsonrpc get; set;
public class Params
[JsonPropertyName("name")]
public string Name get; set;
[JsonPropertyName("options")]
public Options Options get; set;
public class Options
[JsonPropertyName("include_print_record")]
public bool IncludePrintRecord get; set;
[JsonPropertyName("include_layout")]
public bool IncludeLayout get; set;
// Entry Point For Example.
public void Bar()
string input =
"\"method\": \"api.notifications.add\"," +
"\"params\": " +
"\"name\": \"sequence.state.changed\"," +
"\"options\": " +
"\"include_print_record\": true,\"" +
"include_layout\": true" +
"," +
"\"id\": 0," +
"\"jsonrpc\": \"2.0\"" +
"";
MyInputObject inputObject = JsonSerializer.Deserialize<MyInputObject>(input);
那么如果你需要将你的对象转换回 Json 字符串
string jsonResponse = JsonSerializer.Serialize(inputObject);
【讨论】:
OP 想要的另一个关键是格式化。如果您在序列化中添加格式选项,那就太棒了。 虽然不一定是我所要求的我真正需要的好工作 AndrewE。 尝试通过 tcp 连接发送数据,然后收到连续响应。在非常努力地乘坐奋斗巴士之前,从来没有在这个级别上做过任何事情。【参考方案2】:你可以用双引号(“”)来支持多行:
var input = @"
""method"": ""api.notifications.add"",
""params"":
""name"": ""sequence.state.changed"",
""options"":
""include_print_record"": true,
""include_layout"": true
,
""id"": 0,
""jsonrpc"": ""2.0""
";
dotnet 小提琴链接:https://dotnetfiddle.net/5sBzS1
【讨论】:
以上是关于C#多行多双引号字符串的主要内容,如果未能解决你的问题,请参考以下文章