Question

How to Convert a C# Object to a JSON String in .NET

csharp.netjsonserialization

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

A serializer handles the conversion for you. That is much safer and easier than manually building a string, because it correctly escapes characters, handles nested objects, and follows JSON rules.

In .NET, serialization support depends on the framework version:

  • .NET Framework can use built-in serializers such as JavaScriptSerializer or DataContractJsonSerializer
  • Modern .NET commonly uses System.Text.Json
  • Many real-world projects also use Newtonsoft.Json (JSON.NET)

For a .NET 4-era question, the built-in answer is usually JavaScriptSerializer from System.Web.Script.Serialization, or DataContractJsonSerializer from System.Runtime.Serialization.Json.

One important detail: serializers usually work with public properties much better than private fields. That is why examples often use { get; set; } properties instead of plain fields.

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.

Take Quiz

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 = new MyDate
            {
                Year = 1901,
                Month = 4,
                Day = 30
            }
        };

        var serializer = new JavaScriptSerializer();
        string json = serializer.Serialize(lad);

        Console.WriteLine(json);
    }
}

Example output:

{"FirstName":"Markoff","LastName":"Chaney","DateOfBirth":{"Year":1901,"Month":4,"Day":30}}

What this does

  • Creates an object with nested data
  • Uses JavaScriptSerializer to convert it to JSON
  • Produces valid JSON without manually building the string

Another built-in option: DataContractJsonSerializer

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

[DataContract]
public class MyDate
{
    [DataMember]
    public int Year { get; set; }

    [DataMember]
    public int Month { get; set; }

    [DataMember]
    public int Day { get; set; }
}

[DataContract]
public class Lad
{
    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }

    [DataMember]
    public MyDate DateOfBirth { get; set; }
}

class Program
{
    static void Main()
    {
        var lad = new Lad
        {
            FirstName = "Markoff",
            LastName = "Chaney",
            DateOfBirth = new MyDate
            {
                Year = 1901,
                Month = 4,
                Day = 30
            }
        };

        var serializer = new DataContractJsonSerializer(typeof(Lad));

        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, lad);
            string json = Encoding.UTF8.GetString(stream.ToArray());
            Console.WriteLine(json);
        }
    }
}

This option is more explicit and uses attributes to mark what should be serialized.

Modern .NET example with System.Text.Json

using System;
using System.Text.Json;

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; }
}

var lad = new Lad
{
    FirstName = "Markoff",
    LastName = "Chaney",
    DateOfBirth = new MyDate { Year = 1901, Month = 4, Day = 30 }
};

string json = JsonSerializer.Serialize(lad);
Console.WriteLine(json);

This is not available in classic .NET 4, but it is useful to know for current C# development.

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

  1. Create a Lad object

    • FirstName becomes "Markoff"
    • LastName becomes "Chaney"
    • DateOfBirth becomes another object of type MyDate
  2. Create the serializer

    • new JavaScriptSerializer() creates a helper that knows how to turn objects into JSON
  3. Call Serialize(lad)

    • The serializer inspects the Lad object
    • It finds its public properties
    • It reads each property value
    • When it reaches DateOfBirth, it sees a nested object and serializes that too
  4. Generate the JSON string

    • Strings are quoted
    • Numbers stay as numbers
    • Nested objects are wrapped in {}
  5. Print the result

    • Console.WriteLine(json) outputs the final JSON text

Result

{"FirstName":"Markoff","LastName":"Chaney","DateOfBirth":{"Year":1901,"Month":4,"Day":30}}

Important note about property names

Your desired JSON uses camelCase like firstName, while basic C# property names are usually PascalCase like FirstName.

Older built-in serializers often keep the C# names as-is unless you configure attributes or use a different serializer. So the exact output shape may vary depending on the serializer you choose.

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.

Take Quiz

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.

var payload = new
{
    firstName = lad.FirstName,
    lastName = lad.LastName,
    dateOfBirth = new
    {
        year = lad.DateOfBirth.Year,
        month = lad.DateOfBirth.Month,
        day = lad.DateOfBirth.Day
    }
};

Configuration and serializer settings

In real codebases, naming style, null handling, date formatting, and indentation are often configured globally.

Error handling

Serialization can fail for unsupported types or invalid object graphs, so production code may catch and log exceptions where appropriate.

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 firstName.

Avoid this by

  • checking serializer defaults
  • using attributes or naming settings if needed
  • mapping to an anonymous object with the desired names

4. Forgetting nested objects can be null

Problem

int year = lad.DateOfBirth.Year;

If DateOfBirth is null, this throws a NullReferenceException.

Better

Validate before using nested values.

5. Confusing JSON numbers with strings

In JSON, these are different:

{ "year": 1901 }
{ "year": "1901" }

If your C# type is int, a serializer will usually output a number, not a string. That is normally the correct behavior.

6. Missing assembly references

For JavaScriptSerializer, you may need to reference System.Web.Extensions in your project.

Comparisons

OptionBuilt into .NET Framework?External package?Good forNotes
JavaScriptSerializerYesNoSimple JSON serialization in older .NET Framework appsEasy to use, available in System.Web.Script.Serialization
DataContractJsonSerializerYesNoMore explicit serialization with attributesRequires [DataContract] and [DataMember] in many cases
System.Text.JsonNo for .NET 4No in modern .NETModern .NET appsFast and built into newer .NET versions
Newtonsoft.JsonNoYesFlexible real-world serializationVery popular, rich features

Manual string building vs serializer

ApproachProsCons
Manual JSON string buildingNo dependency, full controlError-prone, hard to maintain, unsafe escaping
SerializerSafer, easier, handles nested objectsRequires learning serializer behavior

Fields vs properties

Member typeSerialization friendliness
Private fieldsOften ignored
Public fieldsSometimes supported, less common style
Public propertiesBest default choice
Take Quiz

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, JavaScriptSerializer is a common built-in choice

Quick example

var lad = new Lad
{
    FirstName = "Markoff",
    LastName = "Chaney",
    DateOfBirth = new MyDate { Year = 1901, Month = 4, Day = 30 }
};

string json = new JavaScriptSerializer().Serialize(lad);

Common reference needed

  • System.Web.Extensions for JavaScriptSerializer

Edge cases

  • null values may appear as null in JSON
  • Name casing may not match your target API automatically
  • Circular references can cause problems with some serializers

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.

Take Quiz

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

  1. Create MyDate and Lad classes using public properties.
  2. Create one Lad object with sample data.
  3. Serialize the object to JSON using a built-in .NET Framework serializer.
  4. Print the JSON string to the console.
  5. Make sure the nested DateOfBirth object appears in the output.
Take Quiz

Keep learning

Related questions

View more