最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

.NET?6中System.Text.Json的七個(gè)特性

 更新時(shí)間:2022年01月07日 08:45:47   作者:Oleg?Kyrylchuk  
這篇文章介紹了.NET?6中System.Text.Json的七個(gè)特性,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

忽略循環(huán)引用

在 .NET 5 中,如果存在循環(huán)依賴, 那么序列化的時(shí)候會(huì)拋出異常, 而在 .NET 6 中, 你可以選擇忽略它。

Category dotnet = new()
{
    Name = ".NET 6",
};
Category systemTextJson = new()
{
    Name = "System.Text.Json",
    Parent = dotnet
};
dotnet.Children.Add(systemTextJson);

JsonSerializerOptions options = new()
{
    ReferenceHandler = ReferenceHandler.IgnoreCycles,
    WriteIndented = true
};

string dotnetJson = JsonSerializer.Serialize(dotnet, options);
Console.WriteLine($"{dotnetJson}");

public class Category
{
    public string Name { get; set; }
    public Category Parent { get; set; }
    public List<Category> Children { get; set; } = new();
}

// 輸出:
// {
//   "Name": ".NET 6",
//   "Parent": null,
//   "Children": [
//     {
//       "Name": "System.Text.Json",
//       "Parent": null,
//       "Children": []
//     }
//   ]
// }

序列化和反序列化通知

在 .NET 6 中,System.Text.Json 公開序列化和反序列化的通知。

有四個(gè)新接口可以根據(jù)您的需要進(jìn)行實(shí)現(xiàn):

  • IJsonOnDeserialized
  • IJsonOnDeserializing
  • IJsonOnSerialized
  • IJsonOnSerializing
Product invalidProduct = new() { Name = "Name", Test = "Test" };
JsonSerializer.Serialize(invalidProduct);
// The InvalidOperationException is thrown

string invalidJson = "{}";
JsonSerializer.Deserialize<Product>(invalidJson);
// The InvalidOperationException is thrown

class Product : IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized
{
    public string Name { get; set; }

    public string Test { get; set; }

    public void OnSerialized()
    {
        throw new NotImplementedException();
    }

    void IJsonOnDeserialized.OnDeserialized() => Validate(); // Call after deserialization
    void IJsonOnSerializing.OnSerializing() => Validate();   // Call before serialization

    private void Validate()
    {
        if (Name is null)
        {
            throw new InvalidOperationException("The 'Name' property cannot be 'null'.");
        }
    }
}

 序列化支持屬性排序

在 .NET 6 中, 添加了 JsonPropertyOrderAttribute 特性,允許控制屬性的序列化順序,以前,序列化順序是由反射順序決定的。

Product product = new()
{
    Id = 1,
    Name = "Surface Pro 7",
    Price = 550,
    Category = "Laptops"
};

JsonSerializerOptions options = new() { WriteIndented = true };
string json = JsonSerializer.Serialize(product, options);
Console.WriteLine(json);

class Product : A
{
    [JsonPropertyOrder(2)]  
    public string Category { get; set; }

    [JsonPropertyOrder(1)]  
    public decimal Price { get; set; }

    public string Name { get; set; }  

    [JsonPropertyOrder(-1)]  
    public int Id { get; set; }
}

class A
{
    public int Test { get; set; }
}

// 輸出:
// {
//   "Id": 1,
//   "Name": "Surface Pro 7",
//   "Price": 550,
//   "Category": "Laptops"
// }

使用 Utf8JsonWriter 編寫 JSON

.NET 6 增加了 System.Text.Json.Utf8JsonWriter,你可以方便的用它編寫原始Json。

JsonWriterOptions writerOptions = new() { Indented = true, };

using MemoryStream stream = new();
using Utf8JsonWriter writer = new(stream, writerOptions);

writer.WriteStartObject();
writer.WriteStartArray("customJsonFormatting");
foreach (double result in new double[] { 10.2, 10 })
{
    writer.WriteStartObject();
    writer.WritePropertyName("value");
    writer.WriteRawValue(FormatNumberValue(result), skipInputValidation: true);
    writer.WriteEndObject();
}
writer.WriteEndArray();
writer.WriteEndObject();
writer.Flush();

string json = Encoding.UTF8.GetString(stream.ToArray());
Console.WriteLine(json);

static string FormatNumberValue(double numberValue)
{
    return numberValue == Convert.ToInt32(numberValue)
        ? numberValue.ToString() + ".0"
        : numberValue.ToString();
}

// 輸出:
// {
//    "customJsonFormatting": [
//      {
//        "value": 10.2
//      },
//      {
//        "value": 10.0
//      }
//  ]
// }

IAsyncEnumerable 支持

在 .NET 6 中, System.Text.Json 支持 IAsyncEnumerable。

static async IAsyncEnumerable<int> GetNumbersAsync(int n)
{
    for (int i = 0; i < n; i++)
    {
        await Task.Delay(1000);
        yield return i;
    }
}
// Serialization using IAsyncEnumerable
JsonSerializerOptions options = new() { WriteIndented = true };
using Stream 輸出Stream = Console.OpenStandard輸出();
var data = new { Data = GetNumbersAsync(5) };
await JsonSerializer.SerializeAsync(輸出Stream, data, options);
// 輸出:
// {
//    "Data": [
//      0,
//      1,
//      2,
//      3,
//      4
//  ]
// }

// Deserialization using IAsyncEnumerable
using MemoryStream memoryStream = new(Encoding.UTF8.GetBytes("[0,1,2,3,4]"));
// Wraps the UTF-8 encoded text into an IAsyncEnumerable<T> that can be used to deserialize root-level JSON arrays in a streaming manner.
await foreach (int item in JsonSerializer.DeserializeAsyncEnumerable<int>(memoryStream))
{
    Console.WriteLine(item);
}
// 輸出:
// 0
// 1
// 2
// 3
// 4

IAsyncEnumerable 的序列化的動(dòng)圖。

序列化支持流

在 .NET 6 中, 序列化和反序列化支持流。

string json = "{\"Value\":\"Deserialized from stream\"}";
byte[] bytes = Encoding.UTF8.GetBytes(json);

// Deserialize from stream
using MemoryStream ms = new MemoryStream(bytes);
Example desializedExample = JsonSerializer.Deserialize<Example>(ms);
Console.WriteLine(desializedExample.Value);
// 輸出: Deserialized from stream

// ==================================================================

// Serialize to stream
JsonSerializerOptions options = new() { WriteIndented = true };
using Stream 輸出Stream = Console.OpenStandard輸出();
Example exampleToSerialize = new() { Value = "Serialized from stream" };
JsonSerializer.Serialize<Example>(輸出Stream, exampleToSerialize, options);
// 輸出:
// {
//    "Value": "Serialized from stream"
// }

class Example
{
    public string Value { get; set; }
}

像 DOM 一樣使用 JSON

.NET 6 添加了下面的新類型, 支持像操作 DOM 一樣訪問 Json 元素。

  • JsonArray
  • JsonNode
  • JsonObject
  • JsonValue
// Parse a JSON object
JsonNode jNode = JsonNode.Parse("{\"Value\":\"Text\",\"Array\":[1,5,13,17,2]}");
string value = (string)jNode["Value"];
Console.WriteLine(value); // Text
                          // or
value = jNode["Value"].GetValue<string>();
Console.WriteLine(value); // Text

int arrayItem = jNode["Array"][1].GetValue<int>();
Console.WriteLine(arrayItem); // 5
                              // or
arrayItem = jNode["Array"][1].GetValue<int>();
Console.WriteLine(arrayItem); // 5

// Create a new JsonObject
var jObject = new JsonObject
{
    ["Value"] = "Text",
    ["Array"] = new JsonArray(1, 5, 13, 17, 2)
};
Console.WriteLine(jObject["Value"].GetValue<string>());  // Text
Console.WriteLine(jObject["Array"][1].GetValue<int>());  // 5

// Converts the current instance to string in JSON format
string json = jObject.ToJsonString();
Console.WriteLine(json); // {"Value":"Text","Array":[1,5,13,17,2]}

以上所述是小編給大家介紹的.NET 6中System.Text.Json的七個(gè)特性,希望對(duì)大家有所幫助。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論

宁波市| 布拖县| 辛集市| 大化| 海南省| 黔南| 新安县| 泾川县| 新建县| 清镇市| 南部县| 库尔勒市| 格尔木市| 法库县| 石景山区| 咸宁市| 高邑县| 清河县| 绍兴市| 兴山县| 绵阳市| 马关县| 吴堡县| 莫力| 行唐县| 叙永县| 萝北县| 紫阳县| 宜黄县| 侯马市| 呼图壁县| 鲁山县| 台湾省| 修水县| 沙雅县| 水城县| 瓦房店市| 汽车| 日土县| 鄂尔多斯市| 宜宾县|