Serialize and deserialize JSON in C#

Serializing and deserializing JSON in C# is a common task when working with web APIs, data storage, and configuration files. JSON (JavaScript Object Notation) is a lightweight data interchange format.

JSON serialization in C#

JSON serialization is the process of converting C# objects into JSON format.

Using Newtonsoft.Json (JSON.NET):

To serialize an object to JSON, you can use the JsonConvert.SerializeObject() method. This method takes an object as input and returns a JSON string as output.

using Newtonsoft.Json; // Create a C# object Person person = new Person { FirstName = "Jenny", LastName = "Penn", Age = 30 }; // Serialize the object to JSON string json = JsonConvert.SerializeObject(person);

In this example, a Person object is serialized to JSON using JsonConvert.SerializeObject.

JSON deserialization in C#

JSON deserialization is the process of converting JSON data back into C# objects.

Using Newtonsoft.Json (JSON.NET):
using Newtonsoft.Json; // JSON data as a string string json = "{\"FirstName\":\"Alice\",\"LastName\":\"Smith\",\"Age\":25}"; // Deserialize JSON to a C# object Person person = JsonConvert.DeserializeObject<Person>(json);

In this example, the JSON data is deserialized into a Person object using JsonConvert.DeserializeObject.

Serializing and deserializing JSON is a common task in many C# applications. By understanding how to use the Newtonsoft.Json library, you can easily serialize and deserialize JSON to and from C# objects.

Customizing Serialization

You can customize the serialization behavior by using attributes from the System.Text.Json.Serialization namespace (available in C# 8.0 and later) or JSON.NET attributes from the Newtonsoft.Json namespace.

Using System.Text.Json:
using System.Text.Json; using System.Text.Json.Serialization; public class Person { [JsonPropertyName("first_name")] public string FirstName { get; set; } [JsonPropertyName("last_name")] public string LastName { get; set; } public int Age { get; set; } } // Serialization string json = JsonSerializer.Serialize(person);

In this example, JsonPropertyName attributes are used to specify custom JSON property names.

Handling Null Values

Both libraries handle null values during serialization and deserialization.

Using Newtonsoft.Json:
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string MiddleName { get; set; }

The NullValueHandling setting can be used to control how null values are handled during serialization.

Error Handling

You should handle exceptions that may occur during deserialization, such as JsonSerializationException.

try { Person person = JsonConvert.DeserializeObject<Person>(json); } catch (JsonSerializationException ex) { Console.WriteLine($"JSON deserialization error: {ex.Message}"); }

JSON Serialization in ASP.NET Web APIs

In ASP.NET Web APIs, you can return objects directly from controller actions, and they are automatically serialized to JSON.

[ApiController] [Route("api/[controller]")] public class PersonController : ControllerBase { [HttpGet] public IActionResult GetPerson() { Person person = new Person { FirstName = "John", LastName = "Doe", Age = 30 }; return Ok(person); // Automatically serialized to JSON } }

Conclusion

Serializing and deserializing JSON in C# involves converting C# objects to JSON format and vice versa. Libraries like JSON.NET (Newtonsoft.Json) or the built-in System.Text.Json provide easy-to-use methods for this purpose, enabling data interchange between C# objects and JSON data sources such as web APIs and configuration files.