Question
I have C# classes like this:
class MyDate
{
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
class Lad
{
public string FirstName { get; set; }
public string LastName { get; set; }
public MyDate DateOfBirth { get; set; }
}
I want to convert a Lad object into a JSON string like this:
{
"firstName": "Markoff",
"lastName": "Chaney",
"dateOfBirth": {
"year": 1901,
"month": 4,
"day": 30
}
}
The final output does not need pretty formatting.
I found some examples online, but one solution uses a namespace that does not seem to exist in .NET 4. I have also heard about JSON.NET, but I would prefer to avoid external libraries if possible.
Are there built-in ways in .NET to serialize an object to JSON, or do I need to manually build the JSON string myself?
Short Answer
By the end of this page, you will understand how object serialization to JSON works in C#, which built-in .NET options are available, when external libraries are commonly used, and how to convert nested objects into valid JSON safely without manually concatenating strings.
Concept
JSON serialization is the process of converting an in-memory object into a JSON text representation.
In C#, this means taking an object such as:
var lad = new Lad
{
FirstName = "Markoff",
LastName = "Chaney",
DateOfBirth = new MyDate
{
Year = 1901,
Month = 4,
Day = 30
}
};
and turning it into a string like:
{"FirstName":"Markoff","LastName":"Chaney","DateOfBirth":{"Year":1901,"Month":4,"Day":30}}
This matters because JSON is one of the most common formats for:
- web APIs
- configuration files
- logging
- data exchange between systems
- frontend and backend communication
Mental Model
Think of JSON serialization like filling out a shipping form.
- Your C# object is the real package.
- JSON is the label attached to it.
- The serializer is the worker who reads the package details and writes them in a standard format.
If you try to write the label by hand every time, you may:
- miss a field
- forget quotes or commas
- format nested objects incorrectly
- break when values contain special characters
A serializer does this automatically and consistently.
Syntax and Examples
Built-in option in .NET Framework: JavaScriptSerializer
using System;
using System.Web.Script.Serialization;
public class MyDate
{
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
public class Lad
{
public string FirstName { get; set; }
public string LastName { get; set; }
public MyDate DateOfBirth { get; set; }
}
class Program
{
static void Main()
{
var lad = new Lad
{
FirstName = "Markoff",
LastName = "Chaney",
DateOfBirth = MyDate
{
Year = ,
Month = ,
Day =
}
};
serializer = JavaScriptSerializer();
json = serializer.Serialize(lad);
Console.WriteLine(json);
}
}
Step by Step Execution
Example
var lad = new Lad
{
FirstName = "Markoff",
LastName = "Chaney",
DateOfBirth = new MyDate
{
Year = 1901,
Month = 4,
Day = 30
}
};
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(lad);
Console.WriteLine(json);
Step by step
-
Create a
LadobjectFirstNamebecomes"Markoff"LastNamebecomes"Chaney"DateOfBirthbecomes another object of typeMyDate
-
Create the serializer
new JavaScriptSerializer()creates a helper that knows how to turn objects into JSON
-
Call
Serialize(lad)
Real World Use Cases
JSON serialization is used everywhere in C# applications.
Web APIs
A controller returns a C# object, and the framework serializes it to JSON for the client.
return Ok(new { message = "Saved", id = 42 });
Saving structured data
An app may save user preferences or temporary state to a JSON file.
File.WriteAllText("settings.json", json);
Sending data to another service
A backend often serializes objects before sending them in HTTP requests.
Logging object state
Developers sometimes serialize small objects for debugging or audit logs.
Caching
Objects can be serialized to JSON and stored in Redis, files, or other storage systems.
Real Codebase Usage
In real projects, developers rarely build JSON strings by hand. Instead, they use serializers in patterns like these:
DTOs for API responses
Teams often create simple classes specifically for serialization.
public class PersonResponse
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
This avoids exposing internal domain objects directly.
Validation before serialization
Developers often check that required data exists before returning or storing JSON.
if (lad == null)
{
throw new ArgumentNullException(nameof(lad));
}
Early returns
If there is no data, code may return early instead of serializing invalid objects.
if (lad.DateOfBirth == null)
{
return "{}";
}
Mapping to output shape
Sometimes the class structure is different from the JSON shape needed by an API. Developers map one object into another before serialization.
Common Mistakes
1. Using fields instead of public properties
Some serializers work best with public properties.
Problem
class Lad
{
string firstName;
string lastName;
}
These are private fields by default, so a serializer may ignore them.
Better
class Lad
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
2. Manually concatenating JSON strings
Problem
string json = "{\"firstName\":\"" + name + "\"}";
This breaks easily if name contains quotes, backslashes, or special characters.
Better
Use a serializer.
3. Expecting exact property casing automatically
A serializer may output FirstName instead of .
Comparisons
| Option | Built into .NET Framework? | External package? | Good for | Notes |
|---|---|---|---|---|
JavaScriptSerializer | Yes | No | Simple JSON serialization in older .NET Framework apps | Easy to use, available in System.Web.Script.Serialization |
DataContractJsonSerializer | Yes | No | More explicit serialization with attributes | Requires [DataContract] and [DataMember] in many cases |
System.Text.Json | No for .NET 4 | No in modern .NET | Modern .NET apps | Fast and built into newer .NET versions |
Cheat Sheet
// .NET Framework option
using System.Web.Script.Serialization;
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(obj);
// .NET Framework alternative
using System.Runtime.Serialization.Json;
// Modern .NET
using System.Text.Json;
string json = JsonSerializer.Serialize(obj);
Rules to remember
- Prefer public properties over private fields
- Do not build JSON manually unless absolutely necessary
- Nested objects are serialized automatically
- Strings become JSON strings
int,bool, and other numeric/boolean types stay as JSON numbers/booleans- Property name casing depends on serializer settings
- In .NET Framework,
JavaScriptSerializeris a common built-in choice
Quick example
var lad = new Lad
{
FirstName = "Markoff",
LastName = "Chaney",
DateOfBirth = new MyDate { Year = , Month = , Day = }
};
json = JavaScriptSerializer().Serialize(lad);
FAQ
How do I convert an object to JSON in C# without external libraries?
Use a built-in serializer such as JavaScriptSerializer or DataContractJsonSerializer in .NET Framework.
What is the built-in JSON serializer in .NET 4?
A common built-in choice is System.Web.Script.Serialization.JavaScriptSerializer.
Do I need to manually build a JSON string in C#?
No. In almost all cases, you should use a serializer instead of string concatenation.
Why is my JSON missing fields?
The serializer may ignore private fields. Use public properties or the correct serialization attributes.
How do I serialize nested objects to JSON?
If the nested object is part of a public property, most serializers will serialize it automatically.
Why are my property names FirstName instead of firstName?
Serializer defaults often use your C# property names directly. Use serializer settings, attributes, or mapping if you need camelCase.
Is JSON.NET required for JSON in C#?
No. It is popular, but .NET Framework also includes built-in serializers.
Which serializer should I use today?
For modern .NET, prefer System.Text.Json. For older .NET Framework projects, JavaScriptSerializer or DataContractJsonSerializer are built-in options.
Mini Project
Description
Build a small C# console program that creates a Lad object with a nested MyDate object and serializes it to JSON. This demonstrates how object graphs are converted into structured JSON text using a built-in serializer instead of manual string concatenation.
Goal
Create a console app that outputs a valid JSON string from a nested C# object.
Requirements
- Create
MyDateandLadclasses using public properties. - Create one
Ladobject with sample data. - Serialize the object to JSON using a built-in .NET Framework serializer.
- Print the JSON string to the console.
- Make sure the nested
DateOfBirthobject appears in the output.
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
C# Type Checking Explained: typeof vs GetType() vs is
Learn when to use typeof, GetType(), and is in C#. Understand exact type checks, inheritance, and safe type testing clearly.
C# Version Numbers Explained: C# vs .NET Framework and Why “C# 3.5” Is Incorrect
Learn the correct C# version numbers, how they map to .NET releases, and why terms like C# 3.5 are inaccurate and confusing.