Deserialize
Learn to convert JSON to objects with JsonSerializer.Deserialize.
From text to object with Deserialize
The Deserialize method turns serialized text back into an object. Call: Person p = JsonSerializer.Deserialize<Person>(text);. The type parameter (<Person>) names the target class.
If the text is not valid format, a JsonException is thrown. Keys missing from the target class are ignored; missing keys take the property's default value (e.g. null or 0). This flexibility makes small structure changes easier to absorb.
Type parameter and generics
Deserialize<T> is a generic method. The type parameter <T> tells what type the text should become. Deserialize<Person>(text) returns a Person; Deserialize<int>(text) returns an int.
The compiler infers the result type from T. So you can assign the result to a var or a typed variable: var p = JsonSerializer.Deserialize<Person>(text);. Generic methods preserve type safety.
Exercise Convert text to object
The text variable below is ready. Convert it to a Person object with JsonSerializer.Deserialize<Person>(text) and print p.Name with Console.WriteLine.
Show example solution
Convert with var p = JsonSerializer.Deserialize<Person>(text);, print with Console.WriteLine(p.Name);.
Example solution:
using System;
using System.Text.Json;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
string text = "{\"Name\":\"Alex\",\"Age\":30}";
var p = JsonSerializer.Deserialize<Person>(text);
Console.WriteLine(p.Name);
}
}
Test yourself
-
Complete the Deserialize call
Person p = JsonSerializer.Deserialize<____>(text);Show answer
Person p = JsonSerializer.Deserialize<Person>(text); -
What does Deserialize<Person>(text) return?
- string
- List<Person>
- Person
- void
Show answer
Person — Correct. Deserialize<Person> returns a Person object; the type parameter sets the return type.
-
Match each method to its direction
- Serialize
- Object to text
- Deserialize
- Text to object
- <Person>
- Target type
- JsonException
- Format error