.NET 6'da 7 System.Text.Json özelliği

Paylaş :

Arayüzü Web, Mobil, Desktop uygulamaları UI programlamaya başlanmadan önceki süreçte başarıya ulaşma yolunda mı? Ve bu doğuştan gelenler nasıl çıktılar?

.NET 6'da 7 System.Text.Json özelliği

Dairesel Referansları Yoksay

.NET 5'te, System.Text.Json kullanarak döngüsel başvurular için başvuruları koruyabilirsiniz. Ama onları görmezden gelemezdin. JsonException dairesel referanslar tespit edilip edilmediğini atılır. .NET 6'da bunları yok sayabilirsiniz.

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

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

(De)Serileştirme Bildirimleri

.NET 6'da System.Text.Json, seri hale getirme (de) için bildirimleri gösterir.

İhtiyaçlarınıza göre uygulayabileceğiniz dört yeni arayüz var:

  • 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'.");
        }
    }
}

Özelliklerin Serileştirme Sırası

.NET 6'da, System.Text.Json'a JsonPropertyOrderAttribute eklenmiştir. Özelliklerin seri hale getirilme sırasının kontrol edilmesini sağlar. Daha önce, serileştirme sırası yansıma sırasına göre belirleniyordu.

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)] // Serialize after Price
    public string Category { get; set; }

    [JsonPropertyOrder(1)] // Serialize after other properties that have default ordering
    public decimal Price { get; set; }

    public string Name { get; set; } // Has default ordering value of 0

    [JsonPropertyOrder(-1)] // Serialize before other properties that have default ordering
    public int Id { get; set; }
}

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

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

Utf8JsonWriter ile Raw JSON yazın

.NET 6, System.Text.Json.Utf8JsonWriter ile ham JSON yazma olanağı sunar.

İstediğiniz zaman yardımcı olur:

  • mevcut JSON'u yeni JSON'a dahil etmek için
  • değerleri varsayılan biçimlendirmeden farklı biçimlendirmek için
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();
}

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

IAsyncSayılandırılabilir Destek

.NET 6'da System.Text.Json, IAsyncEnumerable'ı destekler . IAsyncEnumerable'ın serileştirilmesi onu bir diziye dönüştürür. Kök düzeyi JSON Dizilerinin seri durumdan çıkarılması için DeserializeAsyncEnumerable yöntemi eklendi.

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 outputStream = Console.OpenStandardOutput();
var data = new { Data = GetNumbersAsync(5) };
await JsonSerializer.SerializeAsync(outputStream, data, options);
// Output:
// {
//    "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);
}
// Output:
// 0
// 1
// 2
// 3
// 4

(De)JSON Verilerini Bir Akışa/Akıştan Serileştirme

.NET 6'da, Serialize/Deserialize senkronize yöntemleri için akışlar için aşırı yüklemeler eklendi.

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);
// Output: Deserialized from stream

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

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

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

DOM Gibi JSON ile Çalışın

.NET 6, yapılandırılmış bir veri görünümü içinde JSON öğelerine rastgele erişim için bellek içi yazılabilir belge nesne modelini (DOM) işlemeye yönelik türler sağlar.

Yeni türler:

  • 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 = (int)jNode["Array"][1];
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]}

Github Kaynakları

https://github.com/uzeyir06/IAsyncEnumerableSupport
https://github.com/uzeyir06/Caller-expression-attribute
https://github.com/uzeyir06/AssignmentAndDeclarationInSameDeconstruction

Hesabınızı yönetmek için giriş yapın

veya