0

I want to define a contract for a DTO which a consuming API project will implement and return as JSON.

From my perspective there are three concerns here:

  1. The properties defined by the contract
  2. The implementation (for example, this might be an Entity Framework POCO)
  3. The serialization metadata which defines the returned JSON

I'd like to define these three parts separately, but to the best of my knowledge I have to add the serialization decoration (DataMember attributes etc) in the implemtation of my contract. Which means the implementation is coupled with the JSON representation.

Is it possible to separate this serialization metadata into a separate class?

dbc
  • 104,963
  • 20
  • 228
  • 340
Tom Troughton
  • 3,941
  • 2
  • 37
  • 77
  • 1
    If you are working in full .Net (not .Net core) and are serializing with Json.NET you can use [`MetadataTypeAttribute`](https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute(v=vs.110).aspx). But see [JSON.NET Serializes Empty JSON](https://stackoverflow.com/q/45045546/3744182) for some restrictions in the implementation. – dbc Feb 05 '18 at 09:18
  • Thank you @dbc. I think this is exactly what I was looking for. I am using .NET Core actually, but I see `MetadataTypeAttribute` has been migrated and renamed - https://stackoverflow.com/questions/34576921/asp-net-core-metadatatype-attribute-not-working. I'll try this later on and report back. – Tom Troughton Feb 05 '18 at 11:25
  • Sadly though `ModelMetadataType` is not supported by Json.NET. See [How to use ASP.Net core ModelMetadata attribute](https://stackoverflow.com/q/47164280/3744182) and [*Issue #1349: Add support for ModelMetadataType for dotnetcore like supported MetadataTypeAttribute in previous versions*](https://github.com/JamesNK/Newtonsoft.Json/issues/1349). – dbc Feb 05 '18 at 11:29
  • Yes, I've verified that what you say is correct. It would seem the only option would be to use AutoMapper as suggested below. Thank you for your insights though @dbc. – Tom Troughton Feb 06 '18 at 09:17

1 Answers1

2

I always find creating separate models for each purpose is beneficial then use AutoMapper to map between these model.

You could also create conventions instead but this can sometimes feel like magic.

Kevin Smith
  • 13,746
  • 4
  • 52
  • 77