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'ndan Newtonsoft.Jsontaşıma işlemini kullanıyorsanız bkz . Geçiş yöntemi System.Text.Json.

İpucu

GitHub Copilot ile JSON'a seri hale getirmek için yapay zeka yardımını 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üklemesi 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)

Sizin için serileştirme kodu oluşturmak için GitHub Copilot'ı da kullanabilirsiniz. Yönergeler için bu makaledeki GitHub Copilot 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 = new List<DateTimeOffset>() 
                    { 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 = new[] { "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ülmesi gerekmesidir.

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)

alan Serialize bir Utf8JsonWriter aşırı yükleme de kullanılabilir.

Biçimlendirilmiş JSON'a seri hale getirme

JSON çıkışını oldukça yazdırmak için trueolarak ayarlayınJsonSerializerOptions.WriteIndented:

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)

İpucu

Aynı seçeneklerle tekrar tekrar kullanıyorsanız JsonSerializerOptions , her kullandığınızda yeni JsonSerializerOptions bir örnek 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 GitHub Copilot kullanma

JSON'a seri hale getirmek için kullanılan System.Text.Json kodu oluşturmak için IDE'nizde GitHub Copilot'ı kullanabilirsiniz.

Visual Studio 2022 sürüm 17.8 veya üzerini kullanıyorsanız, JSON'a seri hale getirmek için kullanılan System.Text.Json kodu oluşturmak için Visual Studio'da yapay zeka temelli GitHub Copilot'ı deneyebilirsiniz. Sorunuzu, aşağıdaki örnekte olduğu gibi Copilot sohbet penceresinde bir istem olarak gönderin. Ayrıca, düzenleyici penceresinin kendisinde satır içi sohbeti kullanarak da istem gönderebilirsiniz.

Not

GitHub Copilot yapay zeka ile desteklendiğinden sürprizler ve hatalar mümkündür. Oluşturulan tüm kodları veya önerileri doğruladığından emin olun. GitHub Copilot'ın genel kullanımı, ürün etkisi, insan gözetimi ve gizlilik hakkında daha fazla bilgi için bkz . GitHub Copilot SSS.

Aşağıdaki metinde Copilot Sohbeti için örnek bir istem gösterilmektedir:

Bir nesneyi bir JSON dizesine seri hale getirmek için kullanılacak System.Text.Json kod oluşturun. nesnesi şu alanları içerir: Ad (dize), Soyadı (dize), Yaş (int). Örnek çıkış sağlayın.

gereksinimlerinize uygun nesne alanlarını kullanmak için istemi özelleştirebilirsiniz.

Amacı ayarlamak ve kapsamlı bağlamla daha iyi yanıtlar almak için eğik çizgi komutları, dosyalara, yöntemlere veya sınıflara başvurular ve iş parçacıkları gibi sohbet özelliklerini kullanabilirsiniz. IDE'de açık olan bir projedeki mevcut sınıf için GitHub Copilot'a ile /generate code to serialize #Classname in #Filename to JSONsorabilirsiniz.

Aşağıdaki çıkışta örnek bir Copilot Sohbet yanıtı gösterilmektedir:

Sure! Below is an example of how to use System.Text.Json to serialize an object with the specified fields to a JSON string in C#:

using System;
using System.Text.Json;

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {
        var person = new Person
        {
            FirstName = "John",
            LastName = "Doe",
            Age = 30
        };

        string jsonString = JsonSerializer.Serialize(person);
        Console.WriteLine(jsonString);
    }
}

**Example Output**
{"FirstName":"John","LastName":"Doe","Age":30}

This code defines a `Person` class, creates an instance of it, and then serializes it to a JSON string using `JsonSerializer.Serialize`. The resulting JSON string is then printed to the console.

Copilot bir kod bloğu döndürdüğünde, yanıt kodu kopyalama, kodu yeni bir dosyaya ekleme veya kod çıkışını önizleme seçenekleri içerir.

Not

Sonuçlarınız örnek yanıtlarda gösterilenden farklı olabilir. Yapay zeka modelleri belirlenemez, yani aynı soru sorulduğunda farklı yanıtlar döndürebilirler. Bunun nedeni zaman içindeki ek öğrenme ve uyum, dil varyasyonu, sohbet geçmişiniz gibi bağlam değişiklikleri ve daha fazlası olabilir.

Bir nesneyi bir JSON dizesine seri hale getirmek için Visual Studio'da GitHub Copilot Sohbeti'nin kullanılmasını gösteren animasyonlu ekran görüntüsü.

Daha fazla bilgi için bkz.