.NET - Working with JSON in .NET

Working with JSON in .NET - Serialize and Deserialize in C#

Working with JSON in .NET

JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used for APIs and data exchange in modern applications. In .NET, developers commonly use libraries such as System.Text.Json and Newtonsoft.Json (Json.NET) to parse, serialize, and manipulate JSON data efficiently.

What is JSON?

JSON is a text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data between servers and clients. JSON is easy for humans to read and write and easy for machines to parse and generate.

Example JSON Object:

{
  "name": "John Doe",
  "email": "john@example.com",
  "isActive": true,
  "roles": ["Admin", "Editor"],
  "profile": {
    "age": 30,
    "location": "USA"
  }
}

Working with JSON in .NET

.NET provides robust JSON support through two main libraries:

  • System.Text.Json (built-in since .NET Core 3.0)
  • Newtonsoft.Json (popular third-party library)

Using System.Text.Json in .NET

Adding Namespace

using System.Text.Json;
using System.Text.Json.Serialization;

Define a C# Class

public class User
{
    public string Name { get; set; }
    public string Email { get; set; }
    public bool IsActive { get; set; }
    public List<string> Roles { get; set; }
}

Serialize Object to JSON

User user = new User
{
    Name = "Alice",
    Email = "alice@example.com",
    IsActive = true,
    Roles = new List<string> { "User", "Contributor" }
};

string jsonString = JsonSerializer.Serialize(user);
Console.WriteLine(jsonString);

Deserialize JSON to Object

string jsonInput = @"{
  ""Name"": ""Bob"",
  ""Email"": ""bob@example.com"",
  ""IsActive"": true,
  ""Roles"": [""Admin""]
}";

User userObj = JsonSerializer.Deserialize<User>(jsonInput);
Console.WriteLine(userObj.Name); // Bob

Reading JSON from a File

string fileContent = File.ReadAllText("user.json");
User fileUser = JsonSerializer.Deserialize<User>(fileContent);

Writing JSON to a File

string json = JsonSerializer.Serialize(user);
File.WriteAllText("output.json", json);

Handling JSON Options

var options = new JsonSerializerOptions
{
    WriteIndented = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

string formattedJson = JsonSerializer.Serialize(user, options);

Working with Newtonsoft.Json (Json.NET)

Installing the Package

dotnet add package Newtonsoft.Json

Adding Namespace

using Newtonsoft.Json;

Serialize Object to JSON

string jsonOutput = JsonConvert.SerializeObject(user, Formatting.Indented);
Console.WriteLine(jsonOutput);

Deserialize JSON to Object

string inputJson = @"{ ""Name"":""Charlie"",""Email"":""charlie@example.com"" }";
User newUser = JsonConvert.DeserializeObject<User>(inputJson);

Deserialize JSON to Dynamic Object

dynamic dynUser = JsonConvert.DeserializeObject(inputJson);
Console.WriteLine(dynUser.Name);

Differences: System.Text.Json vs Newtonsoft.Json

Feature System.Text.Json Newtonsoft.Json
Built-in Support Yes (from .NET Core 3.0+) No (needs NuGet)
Performance Faster (highly optimized) Slower
Features Limited features More advanced features (e.g., JObject, JToken)
Null Handling Limited custom null value handling Flexible handling options

Working with JObject and JToken in Newtonsoft.Json

Parsing Arbitrary JSON

string json = @"{ ""id"": 1, ""title"": ""Hello World"" }";
JObject obj = JObject.Parse(json);
Console.WriteLine(obj["title"]);

Iterate Over JSON Properties

foreach (var prop in obj.Properties())
{
    Console.WriteLine($"{prop.Name} = {prop.Value}");
}

Serialize and Deserialize Nested JSON

Nested Classes

public class Profile
{
    public int Age { get; set; }
    public string Location { get; set; }
}

public class Employee
{
    public string Name { get; set; }
    public Profile Profile { get; set; }
}
Employee emp = new Employee
{
    Name = "David",
    Profile = new Profile { Age = 25, Location = "UK" }
};

string jsonNested = JsonSerializer.Serialize(emp, options);

Working with JSON Arrays

List<User> users = new List<User>
{
    new User { Name = "Alice" },
    new User { Name = "Bob" }
};

string jsonArray = JsonSerializer.Serialize(users);

Handling JSON Null Values

public class Product
{
    public string Name { get; set; }
    public string? Description { get; set; }
}

var product = new Product { Name = "Pen" };
var options = new JsonSerializerOptions
{
    IgnoreNullValues = true
};

string json = JsonSerializer.Serialize(product, options);

Customize Property Names with Attributes

public class Order
{
    [JsonPropertyName("order_id")]
    public int OrderId { get; set; }

    [JsonPropertyName("total_amount")]
    public decimal Total { get; set; }
}

Deserialize Partial JSON

public class PartialUser
{
    public string Name { get; set; }
}

string partialJson = @"{ ""Name"": ""Eve"", ""Email"": ""eve@example.com"" }";
PartialUser pUser = JsonSerializer.Deserialize<PartialUser>(partialJson);

Real-World Use Cases

  • Parsing API responses
  • Storing configuration data in JSON files
  • Saving user preferences
  • Logging structured data

Best Practices

  • Use camelCase naming policy when working with JavaScript clients
  • Validate input JSON if received from untrusted sources
  • Use DTOs (Data Transfer Objects) for clean JSON mapping
  • Use System.Text.Json for performance, unless advanced features are required

JSON is a fundamental format in modern .NET applications. Whether you're building REST APIs, microservices, or working with data files, understanding how to serialize and deserialize JSON in .NET using System.Text.Json and Newtonsoft.Json is essential. Mastering JSON handling enables robust and flexible application development in C# and .NET Core or .NET 6/7+.

Continue exploring JSON manipulation techniques to enhance your software development capabilities and stay productive in the .NET ecosystem.

Beginner 5 Hours
Working with JSON in .NET - Serialize and Deserialize in C#

Working with JSON in .NET

JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used for APIs and data exchange in modern applications. In .NET, developers commonly use libraries such as System.Text.Json and Newtonsoft.Json (Json.NET) to parse, serialize, and manipulate JSON data efficiently.

What is JSON?

JSON is a text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data between servers and clients. JSON is easy for humans to read and write and easy for machines to parse and generate.

Example JSON Object:

{ "name": "John Doe", "email": "john@example.com", "isActive": true, "roles": ["Admin", "Editor"], "profile": { "age": 30, "location": "USA" } }

Working with JSON in .NET

.NET provides robust JSON support through two main libraries:

  • System.Text.Json (built-in since .NET Core 3.0)
  • Newtonsoft.Json (popular third-party library)

Using System.Text.Json in .NET

Adding Namespace

using System.Text.Json; using System.Text.Json.Serialization;

Define a C# Class

public class User { public string Name { get; set; } public string Email { get; set; } public bool IsActive { get; set; } public List<string> Roles { get; set; } }

Serialize Object to JSON

User user = new User { Name = "Alice", Email = "alice@example.com", IsActive = true, Roles = new List<string> { "User", "Contributor" } }; string jsonString = JsonSerializer.Serialize(user); Console.WriteLine(jsonString);

Deserialize JSON to Object

string jsonInput = @"{ ""Name"": ""Bob"", ""Email"": ""bob@example.com"", ""IsActive"": true, ""Roles"": [""Admin""] }"; User userObj = JsonSerializer.Deserialize<User>(jsonInput); Console.WriteLine(userObj.Name); // Bob

Reading JSON from a File

string fileContent = File.ReadAllText("user.json"); User fileUser = JsonSerializer.Deserialize<User>(fileContent);

Writing JSON to a File

string json = JsonSerializer.Serialize(user); File.WriteAllText("output.json", json);

Handling JSON Options

var options = new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; string formattedJson = JsonSerializer.Serialize(user, options);

Working with Newtonsoft.Json (Json.NET)

Installing the Package

dotnet add package Newtonsoft.Json

Adding Namespace

using Newtonsoft.Json;

Serialize Object to JSON

string jsonOutput = JsonConvert.SerializeObject(user, Formatting.Indented); Console.WriteLine(jsonOutput);

Deserialize JSON to Object

string inputJson = @"{ ""Name"":""Charlie"",""Email"":""charlie@example.com"" }"; User newUser = JsonConvert.DeserializeObject<User>(inputJson);

Deserialize JSON to Dynamic Object

dynamic dynUser = JsonConvert.DeserializeObject(inputJson); Console.WriteLine(dynUser.Name);

Differences: System.Text.Json vs Newtonsoft.Json

Feature System.Text.Json Newtonsoft.Json
Built-in Support Yes (from .NET Core 3.0+) No (needs NuGet)
Performance Faster (highly optimized) Slower
Features Limited features More advanced features (e.g., JObject, JToken)
Null Handling Limited custom null value handling Flexible handling options

Working with JObject and JToken in Newtonsoft.Json

Parsing Arbitrary JSON

string json = @"{ ""id"": 1, ""title"": ""Hello World"" }"; JObject obj = JObject.Parse(json); Console.WriteLine(obj["title"]);

Iterate Over JSON Properties

foreach (var prop in obj.Properties()) { Console.WriteLine($"{prop.Name} = {prop.Value}"); }

Serialize and Deserialize Nested JSON

Nested Classes

public class Profile { public int Age { get; set; } public string Location { get; set; } } public class Employee { public string Name { get; set; } public Profile Profile { get; set; } }
Employee emp = new Employee { Name = "David", Profile = new Profile { Age = 25, Location = "UK" } }; string jsonNested = JsonSerializer.Serialize(emp, options);

Working with JSON Arrays

List<User> users = new List<User> { new User { Name = "Alice" }, new User { Name = "Bob" } }; string jsonArray = JsonSerializer.Serialize(users);

Handling JSON Null Values

public class Product { public string Name { get; set; } public string? Description { get; set; } } var product = new Product { Name = "Pen" }; var options = new JsonSerializerOptions { IgnoreNullValues = true }; string json = JsonSerializer.Serialize(product, options);

Customize Property Names with Attributes

public class Order { [JsonPropertyName("order_id")] public int OrderId { get; set; } [JsonPropertyName("total_amount")] public decimal Total { get; set; } }

Deserialize Partial JSON

public class PartialUser { public string Name { get; set; } } string partialJson = @"{ ""Name"": ""Eve"", ""Email"": ""eve@example.com"" }"; PartialUser pUser = JsonSerializer.Deserialize<PartialUser>(partialJson);

Real-World Use Cases

  • Parsing API responses
  • Storing configuration data in JSON files
  • Saving user preferences
  • Logging structured data

Best Practices

  • Use camelCase naming policy when working with JavaScript clients
  • Validate input JSON if received from untrusted sources
  • Use DTOs (Data Transfer Objects) for clean JSON mapping
  • Use System.Text.Json for performance, unless advanced features are required

JSON is a fundamental format in modern .NET applications. Whether you're building REST APIs, microservices, or working with data files, understanding how to serialize and deserialize JSON in .NET using System.Text.Json and Newtonsoft.Json is essential. Mastering JSON handling enables robust and flexible application development in C# and .NET Core or .NET 6/7+.

Continue exploring JSON manipulation techniques to enhance your software development capabilities and stay productive in the .NET ecosystem.

Related Tutorials

Frequently Asked Questions for General

line

Copyrights © 2024 letsupdateskills All rights reserved