代码之家  ›  专栏  ›  技术社区  ›  TomSelleck

反序列化到枚举-ArgumentException:未找到请求的值“connected”

  •  0
  • TomSelleck  · 技术社区  · 7 年前

    我正在使用swagger生成的以下代码来构建一个模拟api。尝试将字符串反序列化到枚举时出错。

    代码:

    string exampleJson = null;
    exampleJson = "{\n  \"profileDescription\" : \"profileDescription\",\n  \"videoURL\" : \"http://example.com/aeiou\",\n  \"imageURL\" : \"http://example.com/aeiou\",\n  \"imageURLs\" : [ \"http://example.com/aeiou\", \"http://example.com/aeiou\" ],\n  \"name\" : \"name\",\n  \"connectedStatus\" : \"connected\",\n  \"id\" : \"046b6c7f-0b8a-43b9-b35d-6489e6daee91\",\n  \"businessType\" : \"businessType\",\n  \"infoGatherReason\" : \"infoGatherReason\"\n}";
    
    var example = exampleJson != null
    ? JsonConvert.DeserializeObject<Enterprise>(exampleJson)
    : default(Enterprise);
    

    企业cs:

    [DataContract]
    public partial class Enterprise : IEquatable<Enterprise>
    { 
        [DataMember(Name="id")]
        public Guid? Id { get; set; }
    
        [DataMember(Name="name")]
        public string Name { get; set; }
    
        [DataMember(Name="imageURL")]
        public string ImageURL { get; set; }
    
        [DataMember(Name="profileDescription")]
        public string ProfileDescription { get; set; }
    
        [DataMember(Name="infoGatherReason")]
        public string InfoGatherReason { get; set; }
    
        [DataMember(Name="businessType")]
        public string BusinessType { get; set; }
    
        public enum ConnectedStatusEnum
        { 
            [EnumMember(Value = "connected")]
            ConnectedEnum = 1,
    
            [EnumMember(Value = "pending")]
            PendingEnum = 2,
    
            [EnumMember(Value = "notConnected")]
            NotConnectedEnum = 3
        }
    
        [DataMember(Name="connectedStatus")]
        public ConnectedStatusEnum? ConnectedStatus { get; set; }
    
        [DataMember(Name="videoURL")]
        public string VideoURL { get; set; }
    
        [DataMember(Name="imageURLs")]
        public List<string> ImageURLs { get; set; }
    }
    

    错误:

    Newtonsoft.Json.JsonSerializationException: 'Error converting value "connected" to type 'System.Nullable`1[CDPSpecDemo.Models.Enterprise+ConnectedStatusEnum]'. Path 'connectedStatus', line 7, position 33.'
    
    Inner Exception
    
    ArgumentException: Requested value 'connected' was not found.
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   M Bakardzhiev    7 年前

    用JSONConvertertAttribute标记枚举类应该可以

    [JsonConverter(typeof(StringEnumConverter))]
    public enum ConnectedStatusEnum
    { 
        [EnumMember(Value = "connected")]
        ConnectedEnum = 1,
    
        [EnumMember(Value = "pending")]
        PendingEnum = 2,
    
        [EnumMember(Value = "notConnected")]
        NotConnectedEnum = 3
    }