0

We have several complex classes with a variety of decimal (and other) properties. Of the dozens of decimal properties, they all fall under 3 specific formatting rules:

  1. Leading zero, one decimal place
  2. Leading zero, two decimal places
  3. No leading zero, three decimal places

I'd like to decorate the various DTO decimal properties with a custom attribute to specify the formatting rule like [DecimalFormatRule(Rule = "x.000")].

How do I ensure these formatting rules get applied to the decorated properties without interfering with the de/serialization of the hundreds of other properties defined for these same DTO's?

I'm thinking we need a class that can apply the formatting rules, the custom attribute with a string property to hold the formatting rule, and a custom serializer that looks for the attribute and ONLY deals with those properties. Is this even possible?

Is there a better way? I'm reluctant to write my own serializer - I'd definitely prefer to leverage as much of the awesome ServiceStack code as possible.

ragerxs
  • 13
  • 1
  • Possible duplicate of [JsonSerializer - serialize decimal places with 'N2' formatting](http://stackoverflow.com/questions/17871720/jsonserializer-serialize-decimal-places-with-n2-formatting) – OmG May 12 '17 at 20:07

1 Answers1

1

There isn't property-level annotation formatting available in ServiceStack, but you can do something like ignoring the decimal property and add an additional string property getter that returns the format you want, e.g:

public class Dto
{
    [IgnoreDataMember]
    public decimal Decimal { get; set; }

    public string DecimalFormat => Decimal.ToString("0.##");
}
Community
  • 1
  • 1
mythz
  • 141,670
  • 29
  • 246
  • 390