JSON响应中第一个Enum值未正确映射

时间:2018-12-10 01:57:07

标签: c# asp.net json servicestack

我有以下端点:

        public List<SubBranch> Get(GetSubBranch request)
        {
            SubBranch subBranch = new SubBranch();
            subBranch.BranchId = 1;
            subBranch.Addresses = new List<SubBranchAddress>();
            subBranch.Addresses.Add(new SubBranchAddress { AddressType = AddressType.Postal, City = "A" });
            subBranch.Addresses.Add(new SubBranchAddress { AddressType = AddressType.Test, City = "B" });
            subBranch.Addresses.Add(new SubBranchAddress { AddressType = AddressType.Street, City = "C" });
            return new List<SubBranch> { subBranch };
        }

这是模型:

    public class SubBranch
    {
        public int BranchId { get; set; }
        public List<SubBranchAddress> Addresses { get; set; }
    }
    public class SubBranchAddress
    {        
        public string City { get; set; }
        public AddressType AddressType { get; set; }
    }

    public enum AddressType
    {
        Test,
        Street,
        Postal        
    }

这提供了以下JSON响应:

[
  {
    "BranchId": 1,
    "Addresses": [
      {
        "City": "A",
        "AddressType": "Postal"
      },
      {
        "City": "B"
      },
      {
        "City": "C",
        "AddressType": "Street"
      }
    ]
  }
]

您可以看到AddressType枚举中的第一个值未通过。 我希望"City": "B"下方有"AddressType": "Test"。 我玩过不同数量的枚举值,顺序不同,每次第一个值永远都不会通过。

这是为什么,我该如何解决?

1 个答案:

答案 0 :(得分:1)

这是因为我在AppHosts.cs中拥有JsConfig.ExcludeDefaultValues = true;

我可以通过将其设置为false或为Test使用非默认值来解决它:

public enum AddressType
{
    Test = 1,
    Street,
    Postal        
}