I'm using the following code generated by swagger to stand up a mock api. I'm getting an error while trying to deserialise a string to an enum.
Code:
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);
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; }
}
Error:
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.
答案 0 :(得分:1)
Marking your enum class with JsonConverterAttribute should work
[JsonConverter(typeof(StringEnumConverter))]
public enum ConnectedStatusEnum
{
[EnumMember(Value = "connected")]
ConnectedEnum = 1,
[EnumMember(Value = "pending")]
PendingEnum = 2,
[EnumMember(Value = "notConnected")]
NotConnectedEnum = 3
}