0

I have data stored in a database with short field names to save space. When I load these into my .NET Core app, I convert the data to its C# model. Then, when I pass this to the fronted I want to serialize the JSON to have full field names. So instead of "fN", "firstName".

I know I can use [JsonProperty(PropertyName = "SomeName")] to change serialization/deserialization. What I'm asking is whether there's a way to specify multiple property names for a single field, ideally with some additional "profile" variable so that when I serialize/deserialize from the DB I use the DB profile, and when sending to the client I use the other profile. This way I can either use the short or long names when convenient.

Thanks!

Michael Tontchev
  • 909
  • 8
  • 23
  • You can do this with a custom contract resolver. See [How to ignore JsonProperty(PropertyName = “someName”) when serializing json?](https://stackoverflow.com/q/20622492/10263), which is very similar to your question. – Brian Rogers Jan 01 '21 at 17:22
  • 1
    Here is a demo: https://dotnetfiddle.net/nxp1pZ. I changed the `LongNameContractResolver` from the linked question slightly to add a `CamelCaseNamingStrategy` to fit your use case. – Brian Rogers Jan 01 '21 at 18:31
  • Another example of a configurable contract resolver that allows for alternative names based on context can be found at [this answer](https://stackoverflow.com/a/34365216/3744182) to [JsonProperty WebApi request and response models](https://stackoverflow.com/q/34362628/3744182). – dbc Jan 01 '21 at 18:56

0 Answers0