大数跨境
0
0

.NET 9 Preview 1 Json 改进

.NET 9 Preview 1 Json 改进 amazingdotnet
2024-02-20
1
导读:.NET 9 Preview 1 中的 Json 改进

.NET 9 Preview 1 Json 改进

Intro

.NET 9 preview 1 中在序列化的时候可以指定缩进的字符和个数了,并且引入了一个新的默认的序列化选项 JsonSerializerOptions.Web

Indentation

新增的 API 定义如下:

namespace System.Text.Json
{
    public sealed class JsonSerializerOptions
    {
        public char IndentCharacter { getset; }
        public int IndentSize { getset; }
    }

    public struct JsonWriterOptions
    {
        public char IndentCharacter { getset; }
        public int IndentSize { getset; }
    }
}

namespace System.Text.Json.Serialization
{
    public partial class JsonSourceGenerationOptionsAttribute
    {
        public char IndentCharacter { getset; }
        public int IndentSize { getset; }
    }
}

我们可以在 JsonSerializerOptions/JsonWriterOptions 以及 source generator 中使用

默认的 IndentCharacter 一个空格,默认的 IndentSize2

来看一个简单的使用示例:

var job = new
{
    Id = 1,
    Title = "Engineer"
};

var indentOptions = new JsonSerializerOptions
{
    WriteIndented = true
};
Console.WriteLine(JsonSerializer.Serialize(job, indentOptions));
var indentOptions1 = new JsonSerializerOptions
{
    WriteIndented = true,
    IndentCharacter = '\t',
    IndentSize = 1
};
Console.WriteLine(JsonSerializer.Serialize(job, indentOptions1));

这里我们指定了缩进使用一个 \t 制表符

输出结果如下:

intent output

JsonSerilizationOptions.Web

这个 API 是我提议的,因为已经有 JsonSerilizationOptions.Default 并且,web 已经被使用在了 asp.net core 以及 System.Net.Http.Json 中,有一些我们自己处理的场景里也希望能够使用

但是目前只能 new JsonSerializerOptions(JsonSerializerDefaults.Web) 来使用,而且如果每个地方都需要缓存这个 JsonSerilizationOptions.Web 来避免每次都创建,就会造成不必要的重复缓存,可以参考 CA1869 这个 Analyzer rule https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1869

JsonSerializerOptions.Default 的时候方式一致,使用示例如下:

var job = new
{
    Id = 1,
    Title = "Engineer"
};


Console.WriteLine(JsonSerializer.Serialize(job));
Console.WriteLine(JsonSerializer.Serialize(job, JsonSerializerOptions.Web));

输出结果如下:

Web 默认会使用 CamelCase 的命名策略,所以会看到 web 对应的输出属性名首字母是小写的

References

  • https://github.com/dotnet/runtime/issues/63882
  • https://github.com/dotnet/runtime/pull/95292
  • https://github.com/dotnet/runtime/issues/92181
  • https://github.com/dotnet/runtime/pull/94370


【声明】内容源于网络
0
0
amazingdotnet
dotnet 开发知识库,了不起的 dotnet,dotnet 奇淫怪巧
内容 539
粉丝 0
amazingdotnet dotnet 开发知识库,了不起的 dotnet,dotnet 奇淫怪巧
总阅读167
粉丝0
内容539