1. Remembering JSON
JSON stands for JavaScript Object Notation. Despite the scary word JavaScript in the name, this format is completely language-neutral and friendly to all (well, almost all) programming languages, including C#. It was invented to conveniently and clearly describe data — objects, arrays, lists and dictionaries — as plain text.
In today's world, where almost every program talks to other programs, JSON has become the de-facto standard for serializing and exchanging structured data. It's used everywhere: from REST APIs to storing user settings and even for internal communication between microservices. And there's a good reason — it's human-readable (if the human isn't afraid of curly braces), easy to parse and supported by all modern languages and libraries.
Why not XML?
JSON is simpler, shorter and easier to read than XML. Also, it has less noise and tags, and it maps more naturally to data structures in most programming languages. And you don't have to deal with closing tags, quotes and other XML bureaucracy. In short — JSON is about faster, simpler, more convenient.
2. Main elements of JSON syntax
Imagine JSON as a simple tree (or a matryoshka), made of objects, arrays and primitive values. Here are the "building blocks" we have:
Objects (Objects)
A JSON object is a set of "key: value" pairs wrapped in curly braces { }.
Example:
{
"name": "Alice",
"age": 23
}
In C# such a structure can be represented as a class or a dictionary.
Arrays (Arrays)
A JSON array is an ordered list of elements (values of any type), enclosed in square brackets [ ].
Example:
[1, 2, 3, 42]
Or like this:
[
{"name": "Ivan"},
{"name": "Olga"}
]
In C# — that's List<T>, T[] and similar collections.
Key-value pairs
Keys are always strings (in double quotes!), and values can be any data types allowed in JSON.
Example:
{
"id": 123,
"login": "student",
"isActive": true
}
Data types in JSON
| JSON type | Example | Description |
|---|---|---|
| Number | |
An integer or fractional number |
| String | |
Always in double quotes |
| Boolean | |
A logical value |
| null | |
Absence of a value |
| Object | |
A dictionary or an entity with fields |
| Array | |
A sequence of values |
Example — everything together:
{
"id": 1,
"name": "Bob",
"scores": [10, 20, 30],
"profile": {
"email": "bob@mail.com",
"phone": null
},
"isAdmin": false
}
See how compactly and logically you can describe a whole user object.
3. JSON formatting rules
Strings must always be in double quotes
Even if you really want to use single quotes, JSON won't forgive that. This is correct:
{ "name": "Vera" }
This is an error:
{ 'name': 'Vera' }
Keys are only strings
Unlike C#, where a dictionary key can be an int or an enum, in JSON a key is always a string:
{ "2025": "Year of C#", "favorite": true }
No trailing commas
Unlike C# arrays and objects, an extra comma before a closing bracket is a JSON syntax error!
// ERROR! (the last comma is not allowed)
{
"id": 10,
"name": "Oleg",
}
Correct:
{
"id": 10,
"name": "Oleg"
}
Spaces and line breaks
You can add them for readability; parsers ignore them. Usually for "human" format people use pretty-printed (formatted) JSON, and for network transfer — minified (one line, no spaces).
4. How C# objects are converted to JSON
If you serialize an object using System.Text.Json.JsonSerializer.Serialize(), the object's fields and properties become key-value pairs.
Example C# class and serialization
public class Book
{
public string Title { get; set; }
public int Pages { get; set; }
}
var book = new Book { Title = "CLR via C#", Pages = 900 };
string json = JsonSerializer.Serialize(book);
Console.WriteLine(json); // {"Title":"CLR via C#","Pages":900}
Collections
- List<int> becomes [1,2,3]
- string[] becomes ["hi", "wow"]
- List<Person> — an array of objects
Dictionaries
A dictionary like Dictionary<string, int> becomes an object:
var dict = new Dictionary<string, int>
{
["apples"] = 5, ["bananas"] = 10
};
string json = JsonSerializer.Serialize(dict);
// {"apples":5,"bananas":10}
5. Visual scheme: how JSON is built
Nesting — like a matryoshka
Object
│
├── Pair: "name": "Alex"
├── Pair: "hobbies": array
│ │
│ ├── "skiing"
│ └── "programming"
└── Pair: "profile": object
│
├── "age": 42
└── "city": "Basel"
Result:
{
"name": "Alex",
"hobbies": ["skiing", "programming"],
"profile": {
"age": 42,
"city": "Basel"
}
}
6. Common mistakes and syntax pitfalls
There's no perfect world in programming — even JSON has its traps! If you try to send JSON with wrong quotes, extra commas or keys not wrapped in quotes — the parser will throw an error.
Another "gotcha" is numbers with leading zeros. In JSON that's forbidden (for example, 0123 — error).
Good to know: Some parsers (for example, JavaScript's JSON.parse) are more lenient and might "forgive" small violations. But most "strict" parsers (for example, in C# and .NET) will complain about the slightest syntax error.
7. Examples of converting C# data to JSON
Let's try serializing a complex structure in practice. Our training app grows: suppose we now have a list of students and we want to save them to a JSON file.
Define the class:
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
Fill the list:
var students = new List<Student>
{
new Student { Name = "Anna", Age = 20 },
new Student { Name = "Nikita", Age = 22 }
};
Serialization:
using System.Text.Json;
// Serialize the list of students to a JSON string
string json = JsonSerializer.Serialize(students, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(json);
/*
[
{
"Name": "Anna",
"Age": 20
},
{
"Name": "Nikita",
"Age": 22
}
]
*/
See how convenient it is? Each student is a separate object inside the JSON array.
8. Mini-generator: how to write JSON "by hand"
Sometimes you need to write JSON yourself, for example — to create test data manually. Here's a checklist:
- Outer curly braces — for an object, outer square brackets — for an array.
- Key is always a string in double quotes.
- Values — strings (in double quotes), numbers, true, false, null, object ({}), array ([]).
- Only commas between elements, not after the last one!
- Indentation and spaces for readability (but not required).
GO TO FULL VERSION