如何在C#中格式化JSON主体?

huangapple go评论111阅读模式
英文:

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 }))

这是使用csharprepl的示例:
如何在C#中格式化JSON主体?

更新

根据问题中的示例,可以实现如下:

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 }));

输出结果:
如何在C#中格式化JSON主体?

英文:

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 = &quot;value1&quot;, Prop2 = &quot;value2&quot; };
Console.Write(JsonSerializer.Serialize(s, new JsonSerializerOptions { WriteIndented = true }))

Here's example using csharprepl:
如何在C#中格式化JSON主体?

UPDATE

Given example from question this could be achieved with:

dynamic sorting = new { field = &quot;EventDateTime&quot;, dir = &quot;desc&quot; };
dynamic d = new { id = &quot;123&quot;, SessionId = &quot;&quot;, Sorting = new[] { sorting }, Group = Array.Empty&lt;object&gt;() };
Console.Write(JsonSerializer.Serialize(d, new JsonSerializerOptions { WriteIndented = true }));

And the output:
如何在C#中格式化JSON主体?

huangapple
  • 本文由 发表于 2023年6月26日 14:46:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76554143.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定