JSON & Serialization

Intermediate 15 min read Lesson 5 of 10
The Translator Story: Imagine a French chef (C# Server) trying to talk to a Spanish customer (JavaScript Browser). They don't understand each other! They need a translator. JSON is that translator. It is a simple text format that both languages understand perfectly.

Connecting to C#

In C#, you work with Objects and Classes. The browser doesn't know what a C# Class is. So, we must convert our C# objects into a string format called JSON. This process is called Serialization.

Converting JSON back into a C# object is called Deserialization.

What does JSON look like?

It looks exactly like a C# Dictionary or an anonymous object!

{
  "id": 1,
  "name": "Ali",
  "isDeveloper": true,
  "skills": ["C#", "SQL", "ASP.NET"]
}

Example 1: Serializing C# to JSON

using System.Text.Json;

public class User 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsDeveloper { get; set; }
}

// Inside your code:
var myUser = new User { Id = 1, Name = "Ali", IsDeveloper = true };

// Convert C# Object to JSON string
string jsonString = JsonSerializer.Serialize(myUser);
Console.WriteLine(jsonString); 
// Output: {"Id":1,"Name":"Ali","IsDeveloper":true}

Example 2: Deserializing JSON to C#

string incomingJson = "{\"Id\":2,\"Name\":\"Sarah\",\"IsDeveloper\":false}";

// Convert JSON string back to a C# Object
User newUser = JsonSerializer.Deserialize<User>(incomingJson);

Console.WriteLine(newUser.Name); // Output: Sarah

In ASP.NET Core APIs, you rarely have to do this manually! When you return an object like `return Ok(myUser)`, ASP.NET Core automatically serializes it to JSON for you.

Test Your Knowledge - Take Quiz