Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent ServiceStack from serializing an ENUM

This is my response at the moment... (from my RESTful API)

[
  {
    "batchID": 1,
    "status": "IN_PROGRESS"
  }
]

but what I really want is...

[
  {
    "batchID": 1,
    "status": 10   -- which means "In_progress" in my ENUM
  }
]

here is my c# DTO...

public class ReplyItem
{
    public int BatchID { get; set; }            
    public BatchStatusCodes Status { get; set; }
}

so in the JSON my BatchStatusCode is being serialized into a string, but I'd like it as an integer ,as the ENUM has each value set specifically (goes up in 5's)

One Solution : I know I can just change BatchStatusCodes to an int, and whenever I use it I could cast the ENUM to an integer, but including the ENUM in the reply makes it slightly more self describing.

I was hoping maybe I could use an Attribute or some such fancy trick, or maybe set a service wide variable to not treat enums as they currently are?

like image 643
Ninjanoel Avatar asked Apr 22 '14 13:04

Ninjanoel


2 Answers

You can add a [Flags] attribute to enums you want to be treated as numbers, e.g:

[Flags]
BatchStatusCodes { ... } 

Otherwise you can get ServiceStack.Text to treat all enums as integers with:

JsConfig.TreatEnumAsInteger = true;
like image 169
mythz Avatar answered Sep 18 '22 13:09

mythz


<rant> Although, I would avoid using Magic Numbers at any cost. Just imagine you will need to support this service later and how are you supposed to remeber all those digits... </rant>

Anyway, you mat try telling SS to use UseBclJsonSerializers. In your AppHost configure method add this:

SetConfig(new HostConfig{
     // ...
     UseBclJsonSerializers = true,
     // ...
});
like image 41
iamruss Avatar answered Sep 18 '22 13:09

iamruss