Вопрос

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?

Это было полезно?

Решение

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;

Другие советы

<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,
     // ...
});

Old question, I know, but came up in my search for the same issue. If we have an

public eStatus Status { get; set; }

then we simply add an additional

public int StatusId => (int)Status;

(or public int StatusId { get { return (int)Status } } in old-speak)

You can always mark the original as non-serializable if you don't want it in your serialized output, although bear in mind that it won't deserialize from the number unless you create an equivalent setter.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top