I tried to create a custom JSON converter for ProductId, but the conversion didn’t apply to Swagger UI. It still sees ProductId as id: { value: }. I want it to see only the GUID value as shown in the code.
public class ProductIdJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value is ProductId id)
{
serializer.Serialize(writer, id.value);
}
else
{
writer.WriteNull();
}
}
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
var guid = serializer.Deserialize<Guid>(reader);
return ProductId.Create(guid);
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ProductId);
}
}
productId
[EfCoreValueConverter(typeof(ProductConverter.ProductIdValueConverter))]
[JsonConverter(typeof(ProductConverter.ProductIdJsonConverter))]
[TypeConverter(typeof(ProductConverter.ProductIdTypeConverter))]
public sealed class ProductId : ValueObjectId,IValueObjectId<ProductId>
{
public ProductId(Guid id) : base(id)
{
}
public static ProductId Create(Guid id)
{
return new ProductId(id);
}
public static ProductId CreateUnique()
{
return new(Guid.NewGuid());
}
}
ValueObjectId
public abstract class ValueObjectId : ValueObject
{
public Guid value { get; set; }
protected ValueObjectId(Guid id)
{
value = id;
}
public override IEnumerable<object> GetEqualityComponents()
{
yield return value;
}
}
and i made register for this json converter
builder.Services.AddControllers()
.AddNewtonsoftJson(op =>
{
op.SerializerSettings.Converters.Add(new ProductConverter.ProductIdJsonConverter());
});
and swagger still see the object
enter image description here
I was trying to make customejson converter for productId to custom serilization for json api
but this didn’t work
New contributor
Mohamed Atef is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.