Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core Enum Values not serializing after getting the response

In .Net Web API core solution i have a class(Message) with variables of enum type as mentioned below

public enum MessageCode
{
    [EnumMember]
    NULL_PARAMETER,
    BLANK_PARAMETER,
    EMPTY_PARAMETER,
    INVALID_PARAMETER,
    PARAMETER_TRUNCATED,
    QUERY_NOT_FOUND,
    TERM_NOT_FOUND,
    LIST_NOT_FOUND,
    NO_SEARCH_RESULTS,
    NO_UPDATES,
    NO_DICTIONARY,
    NO_PERMISSION,
    LOCKED_PROTOCOL,
    NO_TERMS_IN_LIST,
    DUPLICATE_TERM
}
public enum MessageType
{
    INFO,
    WARNING,
    ERROR,
    FATAL
}
public class Message
{
    [JsonConverter(typeof(StringEnumConverter))]
    public MessageType MessageType { get; set; }

    public bool MessageTypeSpecified;

    [JsonConverter(typeof(StringEnumConverter))]
    public MessageCode MessageCode { get; set; }

    public bool MessageCodeSpecified;

    public string MessageParameters;

    public string MessageText;
}

While getting the response for the object (Message) using postman the response was as below

 "messages": [
    {
        "messageTypeSpecified": false,
        "messageCodeSpecified": false,
        "messageParameters": null,
        "messageText": "0"
    }
]

I was not able to get the enum values in response. so tried the below options

  1. Decorate the Class Property - https://exceptionnotfound.net/serializing-enumerations-in-asp-net-web-api/
  2. Decorate the Enumeration - https://exceptionnotfound.net/serializing-enumerations-in-asp-net-web-api/
  3. Add the Converter Globally - https://exceptionnotfound.net/serializing-enumerations-in-asp-net-web-api/
  4. Mentioning enum member ([EnumMember]) in each enum values.

Nothing worked out.

like image 628
Rajesh Shanmugam Avatar asked Jun 03 '26 20:06

Rajesh Shanmugam


1 Answers

You accidentally hit a Newtonsoft feature (not very well documented). A longer description can be found in this question.

In short: you have a property named MyPropertyName and one named MyPropertyNameSpecified,i.e Specified appended to other property name, the default behaviour for Newtonsoft is to not serialize MyPropertyName when MyPropertyNameSpecified is false.

The solution to your problem would be either to rename some of the properties or use these settings:

new JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver { IgnoreIsSpecifiedMembers = true }
};

To edit JSON serializer settings in a .NET Core project supply the options in your ConfigureServies method:

services.AddMvc()
    .AddJsonOptions(
        options =>
        {
            options.SerializerSettings.ContractResolver =
                new DefaultContractResolver { IgnoreIsSpecifiedMembers = true };
        });
like image 140
wanton Avatar answered Jun 05 '26 09:06

wanton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!