cilerler cilerler - 1 year ago 197
C# Question

How to serialize an enum with JSON.NET based on an attribute?

Code below generates output as

where I would like to get it as

So simply, I was wondering how to honor
attribute while serializing with JSON.NET?

void Main()
var payload = new GooglePlacesPayload();
payload.Status = StatusCode.InvalidRequest;

public class GooglePlacesPayload
[JsonProperty(PropertyName = "error_message")]
public string ErrorMessage { get; set; }

[JsonProperty(PropertyName = "status")]
public StatusCode Status { get; set; }

public enum StatusCode
// reference
// reference

None = 0,

// indicates that no errors occurred; the place was successfully detected and at least one result was returned.
[JsonProperty(PropertyName = "OK")]
Ok = 1,
// indicates that the search was successful but returned no results. This may occur if the search was passed a latlng in a remote location.
[JsonProperty(PropertyName = "ZERO_RESULTS")]
ZeroResults = 2,
// indicates that you are over your quota. The daily quotas are reset at midnight, Pacific Time.
[JsonProperty(PropertyName = "OVER_QUERY_LIMIT")]
OverQueryLimit = 4,
// indicates that your request was denied, generally because of lack of an invalid key parameter.
[JsonProperty(PropertyName = "REQUEST_DENIED")]
RequestDenied = 8,
// generally indicates that a required query parameter (location or radius) is missing.
[JsonProperty(PropertyName = "INVALID_REQUEST")]
InvalidRequest = 16,

// When the Google Places service returns a status code other than OK, there may be an additional error_message field within the search response object.
// This field contains more detailed information about the reasons behind the given status code.
Positive = Ok | ZeroResults,
Negative = OverQueryLimit | RequestDenied | InvalidRequest


Answer Source

[EnumMember(Value="INVALID_REQUEST")] should do it. Note this is a dotnet core attribute, not newtonsoft-specific, so it may affect other things as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download