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.
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.
{
"name": "John Doe",
"email": "john@example.com",
"isActive": true,
"roles": ["Admin", "Editor"],
"profile": {
"age": 30,
"location": "USA"
}
}
.NET provides robust JSON support through two main libraries:
using System.Text.Json;
using System.Text.Json.Serialization;
public class User
{
public string Name { get; set; }
public string Email { get; set; }
public bool IsActive { get; set; }
public List<string> Roles { get; set; }
}
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);
string jsonInput = @"{
""Name"": ""Bob"",
""Email"": ""bob@example.com"",
""IsActive"": true,
""Roles"": [""Admin""]
}";
User userObj = JsonSerializer.Deserialize<User>(jsonInput);
Console.WriteLine(userObj.Name); // Bob
string fileContent = File.ReadAllText("user.json");
User fileUser = JsonSerializer.Deserialize<User>(fileContent);
string json = JsonSerializer.Serialize(user);
File.WriteAllText("output.json", json);
var options = new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
string formattedJson = JsonSerializer.Serialize(user, options);
dotnet add package Newtonsoft.Json
using Newtonsoft.Json;
string jsonOutput = JsonConvert.SerializeObject(user, Formatting.Indented);
Console.WriteLine(jsonOutput);
string inputJson = @"{ ""Name"":""Charlie"",""Email"":""charlie@example.com"" }";
User newUser = JsonConvert.DeserializeObject<User>(inputJson);
dynamic dynUser = JsonConvert.DeserializeObject(inputJson);
Console.WriteLine(dynUser.Name);
| 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 |
string json = @"{ ""id"": 1, ""title"": ""Hello World"" }";
JObject obj = JObject.Parse(json);
Console.WriteLine(obj["title"]);
foreach (var prop in obj.Properties())
{
Console.WriteLine($"{prop.Name} = {prop.Value}");
}
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);
List<User> users = new List<User>
{
new User { Name = "Alice" },
new User { Name = "Bob" }
};
string jsonArray = JsonSerializer.Serialize(users);
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);
public class Order
{
[JsonPropertyName("order_id")]
public int OrderId { get; set; }
[JsonPropertyName("total_amount")]
public decimal Total { get; set; }
}
public class PartialUser
{
public string Name { get; set; }
}
string partialJson = @"{ ""Name"": ""Eve"", ""Email"": ""eve@example.com"" }";
PartialUser pUser = JsonSerializer.Deserialize<PartialUser>(partialJson);
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.
Copyrights © 2024 letsupdateskills All rights reserved