DSO.Core.JsonSafeReader  ·  .NET  ·  System.Text.Json tabanlı

Parse etmek zorunda olmadığın şeyi parse etme.

Büyük JSON dokümanlarının tamamını deserialize etmeden yalnızca ihtiyaç duyduğun alanları okuyan, streaming, chunk-safe ve sıfır üçüncü parti bağımlılığa sahip hafif bir .NET okuma katmanı. Temelde Utf8JsonReader çalışır.

stream.json → JsonSafeReader.ReadJsonFromStreamAsync(["customer"])
target: customer
🎯
buffer: 4096 B başlangıç → 16 MB sınır skip edilenler heap'e hiç materialize olmaz
neden

Standart deserialize akışı, ihtiyacın olmayan her byte'ı da işler

Elinde metadata, orders, logs, attachments gibi alanlar barındıran büyük bir JSON varsa ve uygulamanın tek ihtiyacı customer alanıysa, geri kalan milyonlarca byte'ı parse edip bellekte tutmaya gerek yok.

✕ Geleneksel deserialize

  • Read Entire Document
  • Parse Entire JSON
  • Deserialize Object
  • Use Required Property

✓ JsonSafeReader

  • customer → Deserialize / Extract
ÖzellikGeleneksel DeserializeJsonSafeReader
Tüm JSON'u parse etmeGenellikleGerekmeyebilir
Target property erişimiSonradan erişimDoğrudan aranabilir
Stream desteğiSenaryoya bağlı
Chunk parsing
JsonReaderState devamlılığı
ArrayPool kullanımıGenellikle yok
Property skipSınırlı
Doğrudan Deserialize<T>
max buffer limitiGenellikle yok
Invalid UTF-8 telemetryGenellikle yok
Üçüncü parti bağımlılık✕ Yok
öne çıkan özellikler

Tek API altında birleşen hız, düşük bellek ve dayanıklılık

🚀

Target-driven parsing

Yalnızca belirlediğin property'leri okur, geri kalanını reader.Skip() ile geçer.

🌊

Chunk-based streaming

4096 byte'lık parçalar halinde okur; tüm stream'i tek seferde belleğe almaz.

🧩

JsonReaderState devamlılığı

Bir token chunk sınırında bölünse bile parser state kaybolmaz, güvenle devam eder.

♻️

ArrayPool<byte>

Streaming API'lerinde buffer'lar pool'dan kiralanır, iş bitince iade edilir.

Stack allocation

1024 byte'a kadar küçük içerikler için stackalloc kullanılır, heap baskısı azalır.

🔒

maxBufferSize koruması

Varsayılan 16 MB sınırı; aşırı büyük bir token sınırsız buffer büyümesine yol açamaz.

🛡️

Geçersiz UTF-8 toleransı

Bozuk byte dizileri U+FFFD ile değiştirilir, uygulama çökmez.

📊

Invalid UTF-8 telemetry

Kaç geçersiz sequence tespit edildiği sayılır ve Trace.TraceWarning ile bildirilir.

📦

UTF-8 BOM desteği

EF BB BF ile başlayan içerikler otomatik tespit edilip temizlenir.

💬

JSON comment desteği

CommentHandling.Skip sayesinde yorum satırı içeren JSON'lar da tolere edilir.

Trailing comma desteği

AllowTrailingCommas hem streaming hem non-streaming yolda tutarlı çalışır.

🎯

Case-insensitive matching

customer, Customer, CUSTOMER aynı hedef sayılır.

mimari

Doğrudan .NET'in düşük seviyeli JSON API'leri üzerine kurulu

Kütüphane kendi JSON parser'ını icat etmez; hız ve Span<byte> desteği için doğrudan Utf8JsonReader'a dayanır. Namespace: DSO.Core.JsonSafeReader, ana sınıf: JsonSafeReader.

            ┌─────────────────────┐
            │     JsonSafeReader  │
            └──────────┬──────────┘
                       
      ┌────────────────┼────────────────┐
      │                │                │
      ▼                ▼                ▼
String Input      Byte Input       Stream Input
      │                │                │
      └────────────────┼────────────────┘
                       ▼
               Utf8JsonReader
                       
            ┌──────────┴──────────┐
            │                     │
            ▼                     ▼
     Property Filter        Exclude Filter
            │                     │
            └──────────┬──────────┘
                       ▼
             Target JSON Element
                       
            ┌──────────┴──────────┐
            │                     │
            ▼                     ▼
     JsonDocument          Direct Deserialize<T>
01

Büyük JSON dosyaları

100 MB — 1 GB+ boyutundaki kaynaklarda yalnızca gereken alanların okunması.

02

Büyük API response'ları

Devasa bir REST response'undan tek bir property'nin çıkarılması.

03

Log processing

Büyük JSON log dosyalarından yalnızca ilgili alanların ayıklanması.

04

ETL / Data pipeline

JSON'un belirli bölümlerinin başka sistemlere aktarılması.

05

Background worker

Uzun süre çalışan servislerde allocation ve memory pressure'ın azaltılması.

06

Configuration okuma

appsettings.json ya da özel config dosyalarının section bazlı okunması.

07

Network streaming

Stream olarak gelen JSON'un tamamını belleğe almadan işlenmesi.

08

API gateway / yüksek throughput

Çok sayıda JSON request'inin düşük GC baskısıyla karşılanması.

kullanım

Birkaç satırda hedefe git

Kaynak kodu projene dahil et: using DSO.Core.JsonSafeReader;

1 · Yalnızca ihtiyacın olan property'yi oku
string json = """
{
    "customer": { "Id": 101, "Name": "Ayşe Yılmaz" },
    "order":    { "OrderId": 5001, "Total": 199.90 }
}
""";
 
JsonElement? customer =
    JsonSafeReader.ReadJsonFromString(
        json,
        new[] { "customer" });
2 · JSON'u doğrudan bir tipe deserialize et
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
}
 
Customer? customer =
    JsonSafeReader.DeserializeFromString<Customer>(
        json,
        new[] { "customer" });
 
// JSON → JsonDocument → JsonElement → GetRawText() → Deserialize
// zincirini atlar; doğrudan JsonSerializer.Deserialize(ref reader, options) kullanır.
3 · Byte array'den okuma
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
 
JsonElement? customer =
    JsonSafeReader.ReadJsonFromBytes(
        jsonBytes,
        new[] { "customer" });
4 · Stream'den doğrudan tipe deserialize
await using FileStream stream =
    File.OpenRead("large-data.json");
 
Customer? customer =
    await JsonSafeReader.DeserializeFromStreamAsync<Customer>(
        stream,
        new[] { "customer" });
 
// büyük token'lar için opsiyonel limit:
// maxBufferSize: 8 * 1024 * 1024
5 · Belirli alanları atla
JsonElement? result =
    JsonSafeReader.ReadJsonFromString(
        json,
        Array.Empty<string>(),
        "logs", "attachments", "audit");
 
// belirtilen property'ler reader.Skip() ile geçilir,
// büyük alt ağaçlar application seviyesinde hiç oluşmaz.
6 · appsettings.json'dan section okuma
JsonElement settings =
    JsonSafeReader.GetAppSetting();
 
JsonElement? database =
    JsonSafeReader.ReadSectionFromAppSetting("Database");
 
// async ve dosya adı belirtilen varyantlar da mevcuttur:
// GetAppSettingWithFileNameAsync("production")
güvenlik ve dayanıklılık

"Safe" yalnızca exception yakalamak değil

Girdi, birden fazla katmandan geçerek işlenir — her katman bir sınıf hatasını önceden kapatır.

Input
 
 ├── Null / Empty validation
 
 ├── BOM handling
 
 ├── UTF-8 fallback              → U+FFFD + Trace warning
 
 ├── Invalid UTF-8 tracking
 
 ├── JSON structural validation
 
 ├── Chunk state preservation    → JsonReaderState + BytesConsumed
 
 ├── Buffer limit                → maxBufferSize (default 16 MB)
 
 └── Meaningful exceptions        → FileNotFoundException / ArgumentException / JsonException
api referansı

Namespace: DSO.Core.JsonSafeReader

JSON Element Reading 3 metod
ReadJsonFromString(string jsonString, string[] targetElements, params string[] excludeElementNames)
ReadJsonFromBytes(ReadOnlySpan<byte> jsonBytes, string[] targetElements, params string[] excludeElementNames)
ReadJsonFromStreamAsync(Stream stream, string[] targetElements, string[]? excludeElementNames = null, int maxBufferSize = ...)
Generic Deserialization 3 metod
DeserializeFromString<T>(string jsonString, string[] targetElements, string[]? excludeElementNames = null, JsonSerializerOptions? options = null)
DeserializeFromBytes<T>(byte[] jsonBytes, string[] targetElements, string[]? excludeElementNames = null, JsonSerializerOptions? options = null)
DeserializeFromStreamAsync<T>(Stream stream, string[] targetElements, string[]? excludeElementNames = null, JsonSerializerOptions? options = null, int maxBufferSize = ...)
Section Reading 3 metod
ReadSectionAsElement(string jsonString, string targetPropertyName)
ReadSectionAsElementFromFilePath(string filePath, string targetPropertyName)
ReadSectionAsElementFromFilePathAsync(string filePath, string targetPropertyName, int maxBufferSize = ...)
App Settings 8 metod
GetAppSetting()
GetAppSettingAsync()
GetAppSetting(string filePath)
GetAppSettingAsync(string filePath)
GetAppSettingAsync(byte[] jsonBytes)
GetAppSettingWithFileNameAsync(string fileName)
ReadSectionFromAppSetting(string name)
ReadSectionFromAppSettingAsync(string name)
Project Settings 4 metod
GetProjectSetting()
GetProjectSettingAsync()
ReadSectionFromProjectSetting(string name)
ReadSectionFromProjectSettingAsync(string name)
kurulum

Bağımsız, hafif, kaynak kodu üzerinden dahil edilir

Harici bir JSON parser ya da üçüncü parti framework gerekmez — tüm işleme System.Text.Json üzerinden yapılır. Kaynak kodunu projene dahil et:

using DSO.Core.JsonSafeReader;
 
JsonElement? result =
    JsonSafeReader.ReadJsonFromString(
        json,
        new[] { "customer" });