Technology

C# JSON: How to Serialize and Deserialize JSON Objects?

c# JSON OBJECTS

Author: Marcin Szolke (Scholke) • www.LOV111VOL.com

Introduction

In modern C# development, JSON (JavaScript Object Notation) is the most common format for exchanging data between applications, web APIs, and databases. Whether you’re building a REST API, a desktop application, or a microservice, understanding how to serialize and deserialize JSON in C# is essential.

In this article, we’ll explore:

  • Serializing C# objects to JSON
  • Deserializing JSON to C# objects
  • Handling complex and nested objects
  • Comparing Text.Json and Newtonsoft.Json

What is JSON?

JSON is a lightweight, text-based data format used for storing and transporting structured data. It consists of:

  • Objects: { “key”: “value” }
  • Arrays: [1, 2, 3]
  • Primitive types: strings, numbers, booleans, and null Example JSON:

{

“Name”: “Task 1”, “Completed”: true,

“Tags”: [“C#”, “JSON”, “Serialization”]

}

Serializing Objects to JSON in C#

Using System.Text.Json (built-in in .NET Core/5+)

using System;

using System.Text.Json; public class TaskItem

{

public string Name { get; set; } public bool Completed { get; set; }

}

class Program

{

static void Main()

{

TaskItem task = new TaskItem { Name = “Learn JSON”, Completed = true }; string json = JsonSerializer.Serialize(task);

Console.WriteLine(json);

// Output: {“Name”:”Learn JSON”,”Completed”:true}

}

}

Using Newtonsoft.Json (Json.NET)

using System;

using Newtonsoft.Json; public class TaskItem

{

public string Name { get; set; } public bool Completed { get; set; }

}

class Program

{

static void Main()

{

TaskItem task = new TaskItem { Name = “Learn JSON”, Completed = true }; string json = JsonConvert.SerializeObject(task); Console.WriteLine(json);

// Output: {“Name”:”Learn JSON”,”Completed”:true}

}

 

}

Deserializing JSON to C# Objects

System.Text.Json

string json = “{\”Name\”:\”Learn JSON\”,\”Completed\”:true}”; TaskItem task = JsonSerializer.Deserialize<TaskItem>(json); Console.WriteLine(task.Name); // Output: Learn JSON Console.WriteLine(task.Completed); // Output: True

Newtonsoft.Json

string json = “{\”Name\”:\”Learn JSON\”,\”Completed\”:true}”; TaskItem task = JsonConvert.DeserializeObject<TaskItem>(json); Console.WriteLine(task.Name); // Output: Learn JSON Console.WriteLine(task.Completed); // Output: True

Handling Complex JSON

For nested objects or arrays:

public class Project

{

public string Name { get; set; }

public List<TaskItem> Tasks { get; set; }

}

string projectJson = @”

{

“”Name””: “”My Project””, “”Tasks””: [

{ “”Name””: “”Task 1″”, “”Completed””: true },

{ “”Name””: “”Task 2″”, “”Completed””: false }

]

}”;

Project project = JsonSerializer.Deserialize<Project>(projectJson); Console.WriteLine(project.Tasks[0].Name); // Output: Task 1

Comparing System.Text.Json and Newtonsoft.Json

Both libraries are widely used for JSON processing in C#, but they have different strengths and ideal use cases.

 

Feature / Task System.Text.Json Newtonsoft.Json (Json.NET)
Namespace System.Text.Json Newtonsoft.Json
Built-in ✅ Included in .NET Core 3.0+ /

.NET 5+

❌ Requires NuGet package
Serialize Object to JSON JsonSerializer.Serializ e(obj) JsonConvert.SerializeObject(o bj)
Deserialize JSON to Object JsonSerializer.Deserial ize<T>(json) JsonConvert.DeserializeObject

<T>(json)

Performance High performance Slightly slower, more features
Handling ✅Supported ✅Supported

 

Feature / Task System.Text.Json Newtonsoft.Json (Json.NET)
Complex/Nested Objects    
Custom Converters ✅Limited, implement

JsonConverter<T>

✅Very flexible
Dynamic JSON / ExpandoObject ❌Limited ✅Fully supported
 

Ignore Null Values

JsonSerializerOptions.I gnoreNullValues or DefaultIgnoreCondition [JsonProperty(NullValueHandli ng=NullValueHandling.Ignore)]
Property Naming Policy JsonNamingPolicy.CamelC ase [JsonProperty(“name”)] or

ContractResolver

Comments / Trailing Commas ❌Not supported in strict mode ✅Supported
Date Handling ISO 8601 default ISO 8601 default, custom formats possible
Version Compatibility Modern .NET Core / .NET 5+ Works in all .NET Framework / .NET Core versions
Recommended Use High-performance apps, modern .NET, APIs Complex JSON, legacy projects, advanced scenarios

Summary:

  • Use Text.Json for speed and simplicity in modern .NET.
  • Use Json for flexibility and advanced scenarios, especially dynamic JSON or legacy projects.

Best Practices

  • Use Text.Json for better performance and built-in support in .NET Core/.NET 5+
  • Use Json when you need advanced features (e.g., flexible converters, dynamic JSON, or older .NET versions)
  • Validate JSON before deserialization to avoid runtime errors
  • Use JsonSerializerOptions to customize property naming, ignore nulls, or control formatting

Conclusion

Working with JSON in C# is straightforward with both System.Text.Json and Newtonsoft.Json. By understanding serialization, deserialization, and handling complex objects, developers can efficiently exchange data between APIs, applications, and databases.

Mastering JSON is essential for modern C# development, especially for web services, desktop apps, and microservices.

About the Author

Marcin Szolke (Scholke) is a .NET software engineer and technical author. He is the creator of LOV111VOL.com, a digital office platform with features like a digital binder, project management tools, and a team password manager.

Marcin specializes in C#, .NET, and WPF, building scalable and secure applications. Learn more:

https://lov111vol.com/about-marcin-scholke

c# JSON OBJECTS

Comments
To Top

Pin It on Pinterest

Share This