using MongoDB.Bson;
using Newtonsoft.Json;
namespace adas_core.Domain.Utils;
///
/// Provides a JSON converter for serializing and deserializing values.
///
///
/// Inherits from to customize JSON representation for the type it targets.
///
public class ObjectIdConverter : JsonConverter
{
///
/// Serializes an instance to JSON by writing its string representation; if the value is not an , writes a JSON null instead.
///
/// The used to emit the JSON output.
/// The value to serialize, expected to be an instance.
/// The invoking this converter.
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value is ObjectId objectId)
// Serializa el ObjectId como un string
writer.WriteValue(objectId.ToString());
else
writer.WriteNull();
}
///
/// Reads a JSON value and converts it to an instance. When the token is a non-empty string different from the default ObjectId representation and parses successfully, the parsed value is returned; otherwise the method falls back to for non-nullable target types or null for nullable target types.
///
/// The JSON reader positioned on the value to deserialize.
/// The target type expected by the deserializer, used to decide between returning or null when the value cannot be parsed.
/// The existing value being populated, passed through from the deserializer.
/// The JSON serializer invoking this converter.
/// An instance when the value can be parsed or when the target type is non-nullable; null when the target type is nullable and no valid value is found.
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue,
JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.String)
{
var stringValue = reader.Value as string;
// Verifica si el valor es el valor predeterminado de ObjectId
if (!string.IsNullOrEmpty(stringValue) &&
stringValue != "000000000000000000000000" &&
ObjectId.TryParse(stringValue, out var oid))
return oid;
}
// Nullables reciben null, no-null vuelven Empty
if (objectType == typeof(ObjectId))
return ObjectId.Empty;
// Retorna null o ObjectId.Empty para manejar el valor predeterminado de ObjectId
return null;
}
///
/// Determines whether the converter can convert the specified type by checking if the type is assignable from .
///
/// The type to evaluate for compatibility with the converter.
/// if can be assigned from ; otherwise, .
public override bool CanConvert(Type objectType)
{
return typeof(ObjectId).IsAssignableFrom(objectType);
}
}