Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Code below generates output as {"error_message":null,"status":"InvalidRequest"} where I would like to get it as {"error_message":null,"status":"INVALID_REQUEST"}

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

void Main()
{
    var payload = new GooglePlacesPayload();
    payload.Status = StatusCode.InvalidRequest;
    JsonConvert.SerializeObject(payload).Dump();
}

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

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

[Flags]
public enum StatusCode
{
    // reference https://developers.google.com/maps/premium/previous-licenses/articles/usage-limits#limitexceeded
    // reference https://developers.google.com/places/web-service/search#PlaceSearchStatusCodes

    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

}
like image 387
cilerler Avatar asked Nov 29 '16 19:11

cilerler


People also ask

Can JSON serialize enums?

Using @JsonValue. We've learned how to use @JsonValue to serialize Enums. We can use the same annotation for deserialization as well. This is possible because Enum values are constants.

How do you serialize an Enum?

In order to serialize Enum, we take the help of ObjectMapper class. We use the writeValueAsString() method of ObjectMapper class for serializing Enum. If we serialize Enum by using the writeValueAsString() method, it will represent Java Enums as a simple string.

Are enums serializable C#?

In C#, enums are backed by an integer. Most tools will serialize or save your enums using that integer value.

How are enums represented in JSON?

JSON has no enum type. The two ways of modeling an enum would be: An array, as you have currently. The array values are the elements, and the element identifiers would be represented by the array indexes of the values.


1 Answers

[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.

like image 95
Dax Fohl Avatar answered Sep 27 '22 18:09

Dax Fohl