Reputation: 157
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
Nothing worked out.
Upvotes: 3
Views: 2192
Reputation: 365
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 };
});
Upvotes: 5