.NET Core 3.0 JsonSerializer中Utf8JsonWriter和Utf8JsonReader使用及示例

本文主要介绍NET Core 3.0 JsonSerializer(System.Text.Json)中,使用Utf8JsonWriter和Utf8JsonReader生成及读取UFT-8编码JSON字符串的方法及示例代码。

1、使用Utf8JsonWriter生成UTF-8编码JSON字符串

var options = new JsonWriterOptions
{
Indented = true
};
using (var stream = new MemoryStream())
{
using (var writer = new Utf8JsonWriter(stream, options))
{
writer.WriteStartObject();
writer.WriteString("date", DateTimeOffset.UtcNow);
writer.WriteNumber("temp", 42);
writer.WriteEndObject();
}
string json = Encoding.UTF8.GetString(stream.ToArray());
Console.WriteLine(json);
}

2、使用Utf8JsonReader读取解析 UTF-8编码的JSON 的字节数组

var options = new JsonReaderOptions
{
    AllowTrailingCommas = true,
    CommentHandling = JsonCommentHandling.Skip
};
Utf8JsonReader reader = new Utf8JsonReader(jsonUtf8, options);
while (reader.Read())
{
    Console.Write(reader.TokenType);
    switch (reader.TokenType)
    {
        case JsonTokenType.PropertyName:
        case JsonTokenType.String:
            {
                string text = reader.GetString();
                Console.Write(" ");
                Console.Write(text);
                break;
            }
        case JsonTokenType.Number:
            {
                int value = reader.GetInt32();
                Console.Write(" ");
                Console.Write(value);
                break;
            }
            // Other token types elided for brevity
    }
    Console.WriteLine();
}

推荐阅读
cjavapy编程之路首页