Is it possible to customize the way types are serialized to the response in ASP.NET Core MVC?
In my particular use case I've got a struct, AccountId, that simply wraps around a Guid:
public readonly struct AccountId
{
public Guid Value { get; }
// ...
}
When I return it from an action method, unsurprisingly, it serializes to the following:
{ "value": "F6556C1D-1E8A-4D25-AB06-E8E244067D04" }
Instead, I'd like to automatically unwrap the Value so it serializes to a plain string:
"F6556C1D-1E8A-4D25-AB06-E8E244067D04"
Can MVC be configured to achieve this?
JsonConverter. JSON.NET is used as the default JSON serializer, so consult their docs.ToStringon your struct. That'll effect more than just serialization, though.JsonConverterfor now and perhaps suggest a more generic solution on MVC issue tracker.