Json Serializer
La clase estática JsonSerializer
proporciona métodos para serializar y deserializar objetos a y desde cadenas JSON, utilizando la biblioteca Newtonsoft.Json. Esta clase actúa como un envoltorio, simplificando el proceso de serialización y deserialización, y permitiendo configuraciones personalizadas.
using NodaTime;using NodaTime.Serialization.JsonNet;
namespace CodeDesignPlus.Net.Serializers;
/// <summary>/// Provides methods for serializing and deserializing objects to and from JSON./// </summary>public static class JsonSerializer{ private static readonly JsonSerializerSettings settings = new();
/// <summary> /// Initializes the <see cref="JsonSerializer"/> class. /// </summary> static JsonSerializer() { settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); }
/// <summary> /// Serializes an object to a JSON string. /// </summary> /// <param name="value">The object to serialize.</param> /// <returns>A JSON string representing the serialized object.</returns> public static string Serialize(object value) { return JsonConvert.SerializeObject(value, settings); }
/// <summary> /// Serializes an object to a JSON string using the specified settings. /// </summary> /// <param name="value">The object to serialize.</param> /// <param name="settings">The settings to use during serialization.</param> /// <returns>A JSON string representing the serialized object.</returns> public static string Serialize(object value, JsonSerializerSettings settings) { settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
return JsonConvert.SerializeObject(value, settings); }
/// <summary> /// Serializes an object to a JSON string using the specified formatting. /// </summary> /// <param name="value">The object to serialize.</param> /// <param name="formatting">The formatting options to use during serialization.</param> /// <returns>A JSON string representing the serialized object.</returns> public static string Serialize(object value, Formatting formatting) { return JsonConvert.SerializeObject(value, formatting, settings); }
/// <summary> /// Serializes an object to a JSON string using the specified formatting and settings. /// </summary> /// <param name="value">The object to serialize.</param> /// <param name="formatting">The formatting options to use during serialization.</param> /// <param name="settings">The settings to use during serialization.</param> /// <returns>A JSON string representing the serialized object.</returns> public static string Serialize(object value, Formatting formatting, JsonSerializerSettings settings) { settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
return JsonConvert.SerializeObject(value, formatting, settings); }
/// <summary> /// Deserializes a JSON string to an object of the specified type. /// </summary> /// <typeparam name="T">The type of the object to deserialize.</typeparam> /// <param name="json">The JSON string to deserialize.</param> /// <returns>An object of the specified type deserialized from the JSON string.</returns> public static T Deserialize<T>(string json) { return JsonConvert.DeserializeObject<T>(json, settings); }
/// <summary> /// Deserializes a JSON string to an object of the specified type using the specified settings. /// </summary> /// <typeparam name="T">The type of the object to deserialize.</typeparam> /// <param name="json">The JSON string to deserialize.</param> /// <param name="settings">The settings to use during deserialization.</param> /// <returns>An object of the specified type deserialized from the JSON string.</returns> public static T Deserialize<T>(string json, JsonSerializerSettings settings) { settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
return JsonConvert.DeserializeObject<T>(json, settings); }
/// <summary> /// Deserializes a JSON string to an object of the specified type. /// </summary> /// <param name="json">The JSON string to deserialize.</param> /// <param name="type">The type of the object to deserialize.</param> /// <returns>An object of the specified type deserialized from the JSON string.</returns> public static object Deserialize(string json, Type type) { return JsonConvert.DeserializeObject(json, type, settings); }
/// <summary> /// Deserializes a JSON string to an object of the specified type using the specified settings. /// </summary> /// <param name="json">The JSON string to deserialize.</param> /// <param name="type">The type of the object to deserialize.</param> /// <param name="settings">The settings to use during deserialization.</param> /// <returns>An object of the specified type deserialized from the JSON string.</returns> public static object Deserialize(string json, Type type, JsonSerializerSettings settings) { settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
return JsonConvert.DeserializeObject(json, type, settings); }}
¿Cómo Funciona?
La clase JsonSerializer
utiliza la biblioteca Newtonsoft.Json bajo el capó. Al llamar a los métodos de serialización, la clase convierte objetos .NET en cadenas JSON. De manera similar, los métodos de deserialización convierten cadenas JSON en objetos .NET. La clase ofrece sobrecargas que permiten especificar configuraciones personalizadas como formato de la salida JSON y opciones de configuración de Newtonsoft.Json a través de JsonSerializerSettings
.
Métodos
La clase JsonSerializer
proporciona los siguientes métodos para serialización y deserialización de objetos:
Serialize
El método Serialize
convierte un objeto .NET en una cadena JSON. Puede aceptar un objeto y devolver una cadena JSON, o un objeto y un objeto JsonSerializerSettings
para configuraciones personalizadas.
Deserialize
El método Deserialize
convierte una cadena JSON en un objeto .NET. Puede aceptar una cadena JSON y devolver un objeto, o una cadena JSON y un objeto JsonSerializerSettings
para configuraciones personalizadas.
Ejemplo de Uso
El ejemplo muestra cómo serializar y deserializar un objeto UserModel
utilizando la clase JsonSerializer
. La clase UserModel
es un modelo simple con propiedades como Id
, Name
, Email
y Birthdate
. Al serializar el objeto, se obtiene una cadena JSON que se imprime en la consola. Luego, la cadena JSON se deserializa en un nuevo objeto UserModel
, y se imprime el nombre del usuario.
using CodeDesignPlus.Net.Serializers;using CodeDesignPlus.Net.Serializers.Sample;
var userModel = new UserModel{ Id = Guid.NewGuid(), Name = "John Doe", Email = "john.doe@codedesignplus.com", Birthdate = DateTime.Now};
var json = JsonSerializer.Serialize(userModel);
Console.WriteLine(json);
var userModelDeserialized = JsonSerializer.Deserialize<UserModel>(json);
Console.WriteLine(userModelDeserialized.Name);
Conclusiones
- La clase
JsonSerializer
simplifica el proceso de serialización y deserialización de objetos .NET a JSON y viceversa. - Proporciona métodos estáticos para la serialización y deserialización básicas, así como métodos sobrecargados para opciones avanzadas.
- Se integra perfectamente con la biblioteca Newtonsoft.Json, aprovechando su funcionalidad.
- Es recomendable utilizar las configuraciones de
JsonSerializerSettings
para escenarios específicos como el manejo de valores nulos o la serialización/deserialización de fechas en formatos concretos.