DataContractJsonSerializer and Enums

后端 未结 5 1683
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 22:42

When I serialize a enum value using DataContractJsonSerializer, it serializes the numerical value of the enum, not the string name.

IE:

enum foo
{
          


        
5条回答
  •  孤城傲影
    2020-12-05 23:17

    To get 2 way serialization/deserilization for wcf json you can add a second get set property of type string, when you're construction your json object in javascript use the string named property, on the server side use the strongly typed enum version: e.g.

    public class DTOSearchCriteria {
      public int ? ManufacturerID { get; set; }
      public int ? ModelID { get; set; }
    
      private SortBy _sort;
    
      public SortBy SortType {
        get { return _sort; }
        set { _sort = value; }
      }
    
      public String Sort {
        get {
          return _sort.ToString();
        }
        set {
          _sort = (SortBy) Enum.Parse(typeof(SortBy), value);
        }
      }
    
      public int PageSize { get; set; }
      public int PageNumber { get; set; }
    }
    
    public enum SortBy {
      PriceDescending,
      PriceAscending
    }
    

提交回复
热议问题