简体   繁体   中英

Deserialize a json in C# with Json.Net (NewtonSoft)

I'm using Newtonsoft.Json (v6.0.0.0) and I'm trying to deserialize a JSON into an enumeration.

I tried to use the attribute EnumMember , wich works for the serialization (send a JSON from a .Net Web API) but does not seem to work for the deserialization.

For begining, I have a model like this:

[JsonObject]
public class MyModel
{
    /// <summary>
    /// Gets or sets the username
    /// </summary>
    [Display(Name = @"UserName")]
    [JsonProperty(PropertyName = "userName", Required = Required.Always)]
    public string UserName { get; set; }

          /* .
             . REST OF THE MODEL
             .
             . */

    /// <summary>
    /// Gets or sets the enum model.
    /// </summary>
    [Display(Name = @"EnumModel")]
    [JsonProperty(PropertyName = "enummodel", Required = Required.Always)]
    public MyEnumModel EnumModel { get; set; }
}

MyEnumModel is an enum with those values:

[JsonConverter(typeof(StringEnumConverter))]
public enum MyEnumModel
{
    [EnumMember(Value = "My Value 1")]
    MyValueOne,

    [EnumMember(Value = "My Value 2")]
    MyValueTwo,

    [EnumMember(Value = "My Value 3")]
    MyValueThree
}

When I serialize this enum, I get the correct value, defined by the attribute EnumMember . So in the result of the call, I have a JSON with value "My Value 1" or "My Value 2" or "My Value 3".

But when I send back the JSON with the same value ("My Value 1" for example), I have this error message:

"The value 'My Value 1' is not valid for EnumModel." 

It seems to not use the EnumMember attribute for the deserialization because when I send the value "MyValueOne", it works.

What did I miss? How the attribute [EnumMember()] really works when I deserialize?

Thanks a lot for the help!

EDIT: JSON sample

{  
   "userName":"testuser@gmail.com",
   "enummodel":"My Value 1"
}

EDIT 2: Model validation

Sorry, but I forgot to mention one important thing. I'm using, in my controller a ModelState validation:

if (!this.ModelState.IsValid)
{
    return this.BadRequest(this.ModelState);
}

I think the json is correctly deserialize with attributes EnumMember but the validation failed because the validator do not use the EnumMember to validate my model? Is it correct?

My problem is in the ModelState validation and not the deserialization. With the EnumMember attribute, everything works fine.

Apparently the ModelState validation does not seem to read EnumMember attributes while validating. But this is an other subject :).

Thanks for the help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM