Condividi tramite


Come scrivere oggetti .NET come JSON (serializzare)

Questo articolo illustra come usare lo spazio dei nomi System.Text.Json per serializzare in JavaScript Object Notation (JSON). Se si sta eseguendo la conversione di codice esistente da Newtonsoft.Json, vedere Come eseguire la migrazione a System.Text.Json.

Suggerimento

È possibile usare l'assistenza per l'intelligenza artificiale per serializzare in JSON con GitHub Copilot.

Per scrivere JSON in una stringa o in un file, chiamare il metodo JsonSerializer.Serialize.

Esempi di serializzazione

L'esempio seguente crea JSON come stringa:

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

L'output JSON viene minimizzato (spazi vuoti, rientro e caratteri di nuova riga vengono rimossi) per impostazione predefinita.

L'esempio seguente usa il codice sincrono per creare un file JSON:

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)

L'esempio seguente usa il codice asincrono per creare un file JSON:

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)

Negli esempi precedenti viene utilizzata l'inferenza del tipo per il tipo serializzato. Un overload di Serialize() accetta un parametro di tipo generico:

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)

È anche possibile usare GitHub Copilot per generare automaticamente il codice di serializzazione. Per istruzioni, vedere la sezione Usare GitHub Copilot in questo articolo.

Comportamento della serializzazione

Quando si usa System.Text.Json indirettamente in un'app ASP.NET Core, alcuni comportamenti predefiniti sono diversi. Per altre informazioni, vedere Riutilizzare le istanze JsonSerializerOptions.

I tipi supportati includono:

È possibile implementare convertitori personalizzati per gestire tipi aggiuntivi o per fornire funzionalità non supportate dai convertitori predefiniti.

Di seguito è riportato un esempio che mostra come viene serializzata una classe che contiene le proprietà della raccolta e un tipo definito dall'utente:

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"
'   ]
' }

Serializzare in UTF-8

Serializzare in una matrice di byte UTF-8 più veloce del 5-10% rispetto all'uso dei metodi basati su stringa. Questo perché i byte (come UTF-8) non devono essere convertiti in stringhe (UTF-16).

Per serializzare in una matrice di byte UTF-8, chiamare il metodo 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)

È disponibile anche un overload Serialize che accetta un Utf8JsonWriter.

Serializzare in JSON formattato

Per stampare in modo corretto l'output JSON, impostare JsonSerializerOptions.WriteIndented su true:

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)

Suggerimento

Se si usa JsonSerializerOptions ripetutamente con le stesse opzioni, non creare una nuova istanza JsonSerializerOptions ogni volta che viene usata. Riutilizzare la stessa istanza per ogni chiamata. Per altre informazioni, vedere Riutilizzare le istanze JsonSerializerOptions.

Usare GitHub Copilot per serializzare in JSON

È possibile usare GitHub Copilot nell'IDE per generare codice che usa System.Text.Json per serializzare in JSON.

Se si usa Visual Studio 2022 versione 17.8 o successiva, è possibile provare GitHub Copilot supportato da IA in Visual Studio per generare un codice che utilizza System.Text.Json per serializzare in JSON. Inviare la domanda e il codice da convertire come richiesta nella finestra di chat Copilot, come nell'esempio seguente. È anche possibile inviare richieste usando chat inline nella finestra dell'editor stessa.

Nota

GitHub Copilot è supportato dall'IA, quindi sono possibili sorprese ed errori. Assicurarsi di verificare il codice o i suggerimenti generati. Per maggiori informazioni sull'uso generale di GitHub Copilot, sull'impatto sul prodotto, sulla supervisione umana e sulla privacy, vedere le Domande frequenti su GitHub Copilot.

Il testo seguente mostra un esempio di richiesta di chat di Copilot:

Generare codice da usare System.Text.Json per serializzare un oggetto in una stringa JSON. L'oggetto contiene i campi seguenti: FirstName (string), Lastname (string), Age (int). Fornire un output di esempio.

È possibile personalizzare la richiesta di usare i campi oggetto in base alle proprie esigenze.

È possibile usare funzionalità di chat, ad esempio comandi barra, riferimenti a file, metodi, classi o thread, per impostare la finalità e ottenere risposte migliori con il contesto con ambito. Per una classe esistente in un progetto aperto nell'IDE, è possibile richiedere GitHub Copilot con /generate code to serialize #Classname in #Filename to JSON

L'output seguente mostra un esempio di risposta Copilot Chat:

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.

Quando Copilot restituisce un blocco di codice, la risposta include opzioni per copiare il codice, inserire il codice in un nuovo file o visualizzare in anteprima l'output del codice.

Nota

I risultati potrebbero essere diversi da quanto illustrato nelle risposte di esempio. I modelli di IA non sono deterministici, il che significa che possono restituire risposte diverse quando viene posta la stessa domanda. Questo potrebbe essere dovuto ad apprendimento e adattamento aggiuntivo nel tempo, alla variazione della lingua, ai cambiamenti nel contesto, ad esempio alla cronologia delle chat e altro ancora.

Screenshot animato che mostra l'uso di GitHub Copilot Chat in Visual Studio per serializzare un oggetto in una stringa JSON.

Per altre informazioni, vedi: