Uredi

Deli z drugimi prek


How to read JSON as .NET objects (deserialize)

This article shows how to use the System.Text.Json namespace to deserialize from JavaScript Object Notation (JSON). If you're porting existing code from Newtonsoft.Json, see How to migrate to System.Text.Json.

A common way to deserialize JSON is to have (or create) a .NET class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer.Deserialize method. For the generic overloads, the generic type parameter is the .NET class. For the non-generic overloads, you pass the type of the class as a method parameter. You can deserialize either synchronously or asynchronously.

Tip

You can use AI assistance to deserialize a JSON string with GitHub Copilot.

Any JSON properties that aren't represented in your class are ignored by default. Also, if any properties on the type are required but not present in the JSON payload, deserialization will fail.

Examples

The following example shows how to deserialize a JSON string:

using System.Text.Json;

namespace DeserializeExtra
{
    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()
        {
            string jsonString =
                """
                {
                  "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"
                  ]
                }
                """;
                
            WeatherForecast? weatherForecast = 
                JsonSerializer.Deserialize<WeatherForecast>(jsonString);

            Console.WriteLine($"Date: {weatherForecast?.Date}");
            Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}");
            Console.WriteLine($"Summary: {weatherForecast?.Summary}");
        }
    }
}
// output:
//Date: 8/1/2019 12:00:00 AM -07:00
//TemperatureCelsius: 25
//Summary: Hot
weatherForecast = JsonSerializer.Deserialize(Of WeatherForecastWithPOCOs)(jsonString)

To deserialize from a file by using synchronous code, read the file into a string, as shown in the following example:

using System.Text.Json;

namespace DeserializeFromFile
{
    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()
        {
            string fileName = "WeatherForecast.json";
            string jsonString = File.ReadAllText(fileName);
            WeatherForecast weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(jsonString)!;

            Console.WriteLine($"Date: {weatherForecast.Date}");
            Console.WriteLine($"TemperatureCelsius: {weatherForecast.TemperatureCelsius}");
            Console.WriteLine($"Summary: {weatherForecast.Summary}");
        }
    }
}
// output:
//Date: 8/1/2019 12:00:00 AM -07:00
//TemperatureCelsius: 25
//Summary: Hot
jsonString = File.ReadAllText(fileName)
weatherForecast1 = JsonSerializer.Deserialize(Of WeatherForecast)(jsonString)

To deserialize from a file by using asynchronous code, call the DeserializeAsync method:

using System.Text.Json;

namespace DeserializeFromFileAsync
{
    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()
        {
            string fileName = "WeatherForecast.json";
            using FileStream openStream = File.OpenRead(fileName);
            WeatherForecast? weatherForecast = 
                await JsonSerializer.DeserializeAsync<WeatherForecast>(openStream);

            Console.WriteLine($"Date: {weatherForecast?.Date}");
            Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}");
            Console.WriteLine($"Summary: {weatherForecast?.Summary}");
        }
    }
}
// output:
//Date: 8/1/2019 12:00:00 AM -07:00
//TemperatureCelsius: 25
//Summary: Hot
Dim openStream As FileStream = File.OpenRead(fileName)
weatherForecast1 = Await JsonSerializer.DeserializeAsync(Of WeatherForecast)(openStream)

Deserialization behavior

The following behaviors apply when deserializing JSON:

When you use System.Text.Json indirectly in an ASP.NET Core app, some default behaviors are different. For more information, see Web defaults for JsonSerializerOptions.

You can implement custom converters to provide functionality that isn't supported by the built-in converters.

Deserialize without a .NET class

If you have JSON that you want to deserialize, and you don't have the class to deserialize it into, you have options other than manually creating the class that you need:

Deserialize from UTF-8

To deserialize from UTF-8, call a JsonSerializer.Deserialize overload that takes a ReadOnlySpan<byte> or a Utf8JsonReader, as shown in the following examples. The examples assume the JSON is in a byte array named jsonUtf8Bytes.

var readOnlySpan = new ReadOnlySpan<byte>(jsonUtf8Bytes);
WeatherForecast deserializedWeatherForecast = 
    JsonSerializer.Deserialize<WeatherForecast>(readOnlySpan)!;
Dim jsonString = Encoding.UTF8.GetString(jsonUtf8Bytes)
weatherForecast1 = JsonSerializer.Deserialize(Of WeatherForecast)(jsonString)
var utf8Reader = new Utf8JsonReader(jsonUtf8Bytes);
WeatherForecast deserializedWeatherForecast = 
    JsonSerializer.Deserialize<WeatherForecast>(ref utf8Reader)!;
' This code example doesn't apply to Visual Basic. For more information, go to the following URL:
' https://learn.microsoft.com/dotnet/standard/serialization/system-text-json-how-to#visual-basic-support

Use GitHub Copilot to deserialize JSON

You can use GitHub Copilot in your IDE to generate code that uses System.Text.Json to deserialize from JSON.

If you're using Visual Studio 2022 version 17.8 or later, you can try the AI-driven GitHub Copilot in Visual Studio to generate code that uses System.Text.Json to deserialize JSON. Submit your question as a prompt in the Copilot chat window, as in the following example. You can also submit prompts using inline chat in the editor window itself.

Note

GitHub Copilot is powered by AI, so surprises and mistakes are possible. Make sure to verify any generated code or suggestions. For more information about the general use of GitHub Copilot, product impact, human oversight, and privacy, see GitHub Copilot FAQs.

The following text shows an example prompt for Copilot Chat:

Generate code to use System.Text.Json to deserialize a JSON string {"FirstName":"John","LastName":"Doe","Age":30} to an equivalent .NET object. Map property names & values. Provide example output.

You can customize the prompt to use a JSON string with property names and values that suit your requirements.

You can use chat features, such as slash commands, references to files, methods, or classes, and threads, to set intent and get better answers with scoped context. For an existing class in a project that's open in the IDE, you can prompt GitHub Copilot with /generate code to dserialize JSON to equivalent .NET object in #Filename.

The following output shows an example Copilot Chat response:

Here's an example of how you can use `System.Text.Json` to deserialize a JSON string into a .NET object 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()
    {
        string jsonString = "{\"FirstName\":\"John\",\"LastName\":\"Doe\",\"Age\":30}";
        Person person = JsonSerializer.Deserialize<Person>(jsonString);
        Console.WriteLine($"FirstName: {person.FirstName}");
        Console.WriteLine($"LastName: {person.LastName}");
        Console.WriteLine($"Age: {person.Age}");
    }
}

**Example Output**
FirstName: John
LastName: Doe
Age: 30

This code defines a Person class with properties that match the JSON string. It then uses `JsonSerializer.Deserialize` to convert the JSON string into a `Person` object and prints the properties to the console.

When Copilot returns a code block, the response includes options to copy the code, insert the code into a new file, or preview the code output.

Note

Your results might be different from what's shown in the example responses. AI models are non-deterministic, which means that they can return different responses when asked the same question. This might be due to additional learning and adaption over time, language variation, changes in context, such as your chat history, and more.

Animated screenshot that shows using GitHub Copilot Chat in Visual Studio to deserialize a JSON string to a .NET object.

For more information, see: