英文:
How can i format a json body in c#?
问题
{
id = "123",
SessionId = "",
Sorting = new[] { new { field = "EventDateTime", dir = "desc" } },
Group = new object[] { }
}
英文:
How can i format the following into a json body in c# ?
{
id = "123"
SessionId =""
Sorting = [{ field = "EventDateTime", dir = "desc" }]
Group = []
}
I would usually declare
var body = new
{
id = "123" ,
SessionId =""
???
}
request.AddJsonBody(body);
But these 2 are not formatting correctly
Sorting = [{ field = "EventDateTime", dir = "desc" }]
Group = []
答案1
得分: 0
以下是您要翻译的内容:
var formatted_json = """
{
"id" = "123"
"SessionId" = ""
"Sorting" = [{ "field" = "EventDateTime", "dir" = "desc" }]
"Group" = []
}
""";
英文:
Raw string literal text - """ in string literals
var formatted_json = """
{
"id" = "123"
"SessionId" = ""
"Sorting" = [{ "field" = "EventDateTime", "dir" = "desc" }]
"Group" = []
}
""";
答案2
得分: 0
你可以使用.NET
中的JsonSerializer
,来自System.Text.Json
命名空间,并指定JsonSerializerOptions
:
class Sample { public string Prop1 { get; set; } public string Prop2 { get; set; } }
var s = new Sample { Prop1 = "value1", Prop2 = "value2" };
Console.Write(JsonSerializer.Serialize(s, new JsonSerializerOptions { WriteIndented = true }))
更新
根据问题中的示例,可以实现如下:
dynamic sorting = new { field = "EventDateTime", dir = "desc" };
dynamic d = new { id = "123", SessionId = "", Sorting = new[] { sorting }, Group = Array.Empty<object>() };
Console.Write(JsonSerializer.Serialize(d, new JsonSerializerOptions { WriteIndented = true }));
英文:
You can use .NET JsonSerializer
from System.Text.Json
namespace with specifying JsonSerializerOptions
:
class Sample { public string Prop1 { get; set; } public string Prop2 { get; set; } }
var s = new Sample { Prop1 = "value1", Prop2 = "value2" };
Console.Write(JsonSerializer.Serialize(s, new JsonSerializerOptions { WriteIndented = true }))
Here's example using csharprepl:
UPDATE
Given example from question this could be achieved with:
dynamic sorting = new { field = "EventDateTime", dir = "desc" };
dynamic d = new { id = "123", SessionId = "", Sorting = new[] { sorting }, Group = Array.Empty<object>() };
Console.Write(JsonSerializer.Serialize(d, new JsonSerializerOptions { WriteIndented = true }));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论