Aracılığıyla paylaş


.NET nesnelerini JSON olarak yazma (serileştirme)

Bu makalede, JavaScript Nesne Gösterimi'ne System.Text.Json (JSON) serileştirmek için ad alanının nasıl kullanılacağı gösterilmektedir. mevcut kodu Newtonsoft.Json'dan taşıyorsanız bkz. System.Text.Json'a nasıl geçiş yapılır.

İpucu

JSON'a seri hale getirmek için yapay zeka yardımı kullanabilirsiniz.

Bir dizeye veya dosyaya JSON yazmak için yöntemini çağırın JsonSerializer.Serialize .

Serileştirme örnekleri

Aşağıdaki örnek JSON'yi dize olarak oluşturur:

using System.Text.Json;

namespace SerializeBasic
{
    public class WeatherForecast
    {
        public DateTimeOffset Date { get; set; }
        public int TemperatureCelsius { get; set; }
        public string? Summary { get; set; }
    }

    public class Program
    {
        public static void Main()
        {
            var weatherForecast = new WeatherForecast
            {
                Date = DateTime.Parse("2019-08-01"),
                TemperatureCelsius = 25,
                Summary = "Hot"
            };

            string jsonString = JsonSerializer.Serialize(weatherForecast);

            Console.WriteLine(jsonString);
        }
    }
}
// output:
//{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"}
Dim jsonString As String

JSON çıkışı varsayılan olarak küçültülür (boşluk, girinti ve yeni satır karakterleri kaldırılır).

Aşağıdaki örnekte bir JSON dosyası oluşturmak için zaman uyumlu kod kullanılmaktadır:

using System.Text.Json;

namespace SerializeToFile
{
    public class WeatherForecast
    {
        public DateTimeOffset Date { get; set; }
        public int TemperatureCelsius { get; set; }
        public string? Summary { get; set; }
    }

    public class Program
    {
        public static void Main()
        {
            var weatherForecast = new WeatherForecast
            {
                Date = DateTime.Parse("2019-08-01"),
                TemperatureCelsius = 25,
                Summary = "Hot"
            };

            string fileName = "WeatherForecast.json"; 
            string jsonString = JsonSerializer.Serialize(weatherForecast);
            File.WriteAllText(fileName, jsonString);

            Console.WriteLine(File.ReadAllText(fileName));
        }
    }
}
// output:
//{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"}
jsonString = JsonSerializer.Serialize(weatherForecast1)
File.WriteAllText(fileName, jsonString)

Aşağıdaki örnekte JSON dosyası oluşturmak için zaman uyumsuz kod kullanılmaktadır:

using System.Text.Json;

namespace SerializeToFileAsync
{
    public class WeatherForecast
    {
        public DateTimeOffset Date { get; set; }
        public int TemperatureCelsius { get; set; }
        public string? Summary { get; set; }
    }

    public class Program
    {
        public static async Task Main()
        {
            var weatherForecast = new WeatherForecast
            {
                Date = DateTime.Parse("2019-08-01"),
                TemperatureCelsius = 25,
                Summary = "Hot"
            };

            string fileName = "WeatherForecast.json";
            await using FileStream createStream = File.Create(fileName);
            await JsonSerializer.SerializeAsync(createStream, weatherForecast);

            Console.WriteLine(File.ReadAllText(fileName));
        }
    }
}
// output:
//{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"}
Dim createStream As FileStream = File.Create(fileName)
Await JsonSerializer.SerializeAsync(createStream, weatherForecast1)

Yukarıdaki örneklerde seri hale getirilen tür için tür çıkarımı kullanılır. Aşırı yükleme Serialize() genel bir tür parametresi alır:

using System.Text.Json;

namespace SerializeWithGenericParameter
{
    public class WeatherForecast
    {
        public DateTimeOffset Date { get; set; }
        public int TemperatureCelsius { get; set; }
        public string? Summary { get; set; }
    }

    public class Program
    {
        public static void Main()
        {
            var weatherForecast = new WeatherForecast
            {
                Date = DateTime.Parse("2019-08-01"),
                TemperatureCelsius = 25,
                Summary = "Hot"
            };

            string jsonString = JsonSerializer.Serialize<WeatherForecast>(weatherForecast);

            Console.WriteLine(jsonString);
        }
    }
}
// output:
//{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"}
jsonString = JsonSerializer.Serialize(Of WeatherForecastWithPOCOs)(weatherForecast)

Ayrıca yapay zekayı kullanarak sizin için serileştirme kodu oluşturabilirsiniz. Yönergeler için bu makaledeki Yapay zekayı kullanma bölümüne bakın.

Serileştirme davranışı

ASP.NET Core uygulamasında dolaylı olarak kullandığınızda System.Text.Json bazı varsayılan davranışlar farklıdır. Daha fazla bilgi için bkz . JsonSerializerOptions için web varsayılanları.

Desteklenen türler şunlardır:

Ek türleri işlemek veya yerleşik dönüştürücüler tarafından desteklenmeyen işlevler sağlamak için özel dönüştürücüler uygulayabilirsiniz.

Koleksiyon özellikleri ve kullanıcı tanımlı bir tür içeren bir sınıfın nasıl seri hale getirildiğini gösteren bir örnek aşağıda verilmiştir:

using System.Text.Json;

namespace SerializeExtra
{
    public class WeatherForecast
    {
        public DateTimeOffset Date { get; set; }
        public int TemperatureCelsius { get; set; }
        public string? Summary { get; set; }
        public string? SummaryField;
        public IList<DateTimeOffset>? DatesAvailable { get; set; }
        public Dictionary<string, HighLowTemps>? TemperatureRanges { get; set; }
        public string[]? SummaryWords { get; set; }
    }

    public class HighLowTemps
    {
        public int High { get; set; }
        public int Low { get; set; }
    }

    public class Program
    {
        public static void Main()
        {
            var weatherForecast = new WeatherForecast
            {
                Date = DateTime.Parse("2019-08-01"),
                TemperatureCelsius = 25,
                Summary = "Hot",
                SummaryField = "Hot",
                DatesAvailable = [DateTime.Parse("2019-08-01"), DateTime.Parse("2019-08-02")],
                TemperatureRanges = new Dictionary<string, HighLowTemps>
                    {
                        ["Cold"] = new HighLowTemps { High = 20, Low = -10 },
                        ["Hot"] = new HighLowTemps { High = 60 , Low = 20 }
                    },
                SummaryWords = ["Cool", "Windy", "Humid"]
            };

            var options = new JsonSerializerOptions { WriteIndented = true };
            string jsonString = JsonSerializer.Serialize(weatherForecast, options);

            Console.WriteLine(jsonString);
        }
    }
}

// Output:
//{
//  "Date": "2019-08-01T00:00:00-07:00",
//  "TemperatureCelsius": 25,
//  "Summary": "Hot",
//  "DatesAvailable": [
//    "2019-08-01T00:00:00-07:00",
//    "2019-08-02T00:00:00-07:00"
//  ],
//  "TemperatureRanges": {
//    "Cold": {
//      "High": 20,
//      "Low": -10
//    },
//    "Hot": {
//    "High": 60,
//      "Low": 20
//    }
//  },
//  "SummaryWords": [
//    "Cool",
//    "Windy",
//    "Humid"
//  ]
//}
Public Class WeatherForecastWithPOCOs
    Public Property [Date] As DateTimeOffset
    Public Property TemperatureCelsius As Integer
    Public Property Summary As String
    Public SummaryField As String
    Public Property DatesAvailable As IList(Of DateTimeOffset)
    Public Property TemperatureRanges As Dictionary(Of String, HighLowTemps)
    Public Property SummaryWords As String()
End Class

Public Class HighLowTemps
    Public Property High As Integer
    Public Property Low As Integer
End Class

' serialization output formatted (pretty-printed with whitespace and indentation):
' {
'   "Date": "2019-08-01T00:00:00-07:00",
'   "TemperatureCelsius": 25,
'   "Summary": "Hot",
'   "DatesAvailable": [
'     "2019-08-01T00:00:00-07:00",
'     "2019-08-02T00:00:00-07:00"
'   ],
'   "TemperatureRanges": {
'     "Cold": {
'       "High": 20,
'       "Low": -10
'     },
'     "Hot": {
'       "High": 60,
'       "Low": 20
'     }
'   },
'   "SummaryWords": [
'     "Cool",
'     "Windy",
'     "Humid"
'   ]
' }

UTF-8'e seri hale getirme

UtF-8 bayt dizisine seri hale getirmek, dize tabanlı yöntemleri kullanmaktan %5-10 daha hızlıdır. Bunun nedeni, baytların (UTF-8 olarak) dizelere (UTF-16) dönüştürülmeye ihtiyaç duymamasıdır.

UTF-8 bayt dizisine seri hale getirmek için yöntemini çağırın JsonSerializer.SerializeToUtf8Bytes :

byte[] jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(weatherForecast);
Dim jsonUtf8Bytes As Byte()
Dim options As JsonSerializerOptions = New JsonSerializerOptions With {
    .WriteIndented = True
}
jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(weatherForecast1, options)

Serialize alan bir Utf8JsonWriter içeren aşırı yükleme de mevcuttur.

Biçimlendirilmiş JSON olarak serileştirmek

JSON çıktısını biçimli yazdırmak için JsonSerializerOptions.WriteIndented öğesini true olarak ayarlayın.

using System.Text.Json;

namespace SerializeWriteIndented
{
    public class WeatherForecast
    {
        public DateTimeOffset Date { get; set; }
        public int TemperatureCelsius { get; set; }
        public string? Summary { get; set; }
    }

    public class Program
    {
        public static void Main()
        {
            var weatherForecast = new WeatherForecast
            {
                Date = DateTime.Parse("2019-08-01"),
                TemperatureCelsius = 25,
                Summary = "Hot"
            };

            var options = new JsonSerializerOptions { WriteIndented = true };
            string jsonString = JsonSerializer.Serialize(weatherForecast, options);

            Console.WriteLine(jsonString);
        }
    }
}
// output:
//{
//  "Date": "2019-08-01T00:00:00-07:00",
//  "TemperatureCelsius": 25,
//  "Summary": "Hot"
//}
Dim options As JsonSerializerOptions = New JsonSerializerOptions With {
    .WriteIndented = True
}
jsonString = JsonSerializer.Serialize(weatherForecast, options)

.NET 9'dan başlayarak, IndentCharacter ve IndentSize kullanarak girinti karakterini ve boyutunu özelleştirebilirsiniz.

İpucu

JsonSerializerOptions 'yi aynı seçeneklerle tekrar tekrar kullanıyorsanız, her seferinde yeni bir JsonSerializerOptions örneği oluşturmayın. Her çağrı için aynı örneği yeniden kullanma. Daha fazla bilgi için bkz . JsonSerializerOptions örneklerini yeniden kullanma.

JSON'a seri hale getirmek için yapay zeka kullanma

JSON'a serileştirmek için System.Text.Json kullanan kodu oluşturmak amacıyla GitHub Copilot gibi yapay zeka araçlarını kullanabilirsiniz. İstemi nesne alanlarınıza ve serileştirme gereksinimlerinize uyacak şekilde özelleştirebilirsiniz.

Serileştirme kodu oluşturmak için kullanabileceğiniz örnek bir istem aşağıda verilmişti:

I have a variable named weatherForecast of type WeatherForecast.
Serialize the variable using System.Text.Json and write the result directly to a file named "output.json" with the JSON indented for pretty formatting.
Ensure the code includes all necessary using directives and compiles without errors.

Uygulamadan önce Copilot'un önerilerini gözden geçirin.

GitHub Copilot hakkında daha fazla bilgi için bkz. GitHub'ın SSS'leri.

Ayrıca bakınız