4

I have a simple class which contains an Enum as a property:

public class MyClass
{
    public MyEnum Type { get; set; }
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

public enum MyEnum
{
    Something,
    OrOther
}

I'm then using this in asp.net web api to model bind:

public async Task<JsonResult> Post([FromBody] MyClass myClass)
{
 //Some exciting controllery type stuff in here....
}

And posting data from Fiddler:

{
"Type":"0", 
"Prop1":"TestValue",
"Prop2":"MoreTestData"
}

And all is working well. Now I want to post to this API from inside a Xamarin application, so use:

var stringData = JsonConvert.SerializeObject(data);

where data is an instance of MyClass but the enum is getting converted to an integer, not its string value. So after a bit of Googling I decorate the enum attribute with

public class MyClass
{
    [JsonConverter(typeof(StringEnumConverter))]
    public MyEnum Type { get; set; }
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

And now my serialization is working correctly and the value is coming through as the string representation of the enum, not the integer value.

However, when I post from Fiddler now, using either the string or the integer, the model binding fails and the value is null.

Is there a way to fix this so that both scenarios will work?

Thanks

1
  • Would you please add resulting JSON (with converter) as well? Commented Dec 12, 2017 at 10:39

1 Answer 1

3

You should add the serialization attribute to your enum definition as well

[JsonConverter(typeof(StringEnumConverter))]
public enum MyEnum
{
    Something,
    OrOther
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.