问题描述
我需要制作这段文字:
{
"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
}
},"jsonrpc": "2.0"
}";
它需要保留它所具有的格式。我尝试了很多方法,包括在每个引号前加一个反斜杠,显然在第一个引号前加一个 @ 符号。
解决方法
你可以用双引号("")来支持多行:
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
,根据您的口味类型,我喜欢使用反斜杠。
string input =
"{\"method\": \"api.notifications.add\"," +
"\"params\": " +
"{\"name\": \"sequence.state.changed\"," +
"\"options\": " +
"{\"include_print_record\": true,\"" +
"include_layout\": true}" +
"}," +
"\"id\": 0," +
"\"jsonrpc\": \"2.0\"" +
"}";
但是,正如上面在评论中提到的,创建 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);