glideapps / quicktype

Generate types and converters from JSON, Schema, and GraphQL
https://app.quicktype.io
Apache License 2.0
12.36k stars 1.07k forks source link

Use StringEnumConverter if applicable in C# #818

Open schani opened 6 years ago

schani commented 6 years ago

It doesn't support arbitrary naming of enum values, so we can't use it in the general case.

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Converters_StringEnumConverter.htm

This might also be applicable:

https://msdn.microsoft.com/en-us/library/system.runtime.serialization.enummemberattribute(v=vs.110).aspx

astrohart commented 3 years ago

Me too. I tried to paste the following code -- which I obtained here, into Quicktype.io:

{
    "errorTypes": [
        {
            "error": "MissingRegistration"
        },
        {
            "error": "InvalidRegistration"
        },
        {
            "error": "NotRegistered"
        },
        {
            "error": "InvalidPackageName"
        },
        {
            "error": "MismatchSenderId"
        },
        {
            "error": "MessageTooBig"
        },
        {
            "error": "InvalidDataKey"
        },
        {
            "error": "InvalidTtl"
        },
        {
            "error": "Unavailable"
        },
        {
            "error": "InternalServerError"
        },
        {
            "error": "DeviceMessageRateExceeded"
        },
        {
            "error": "TopicsMessageRateExceeded"
        }
    ]
}

Fully expecting that it would be converted into

public class SampleEntity
{
    [JsonProperty("error")]
    [JsonConverter(typeof(StringEnumConverter))]
    public ErrorCode Error { get; set; }
}

with a produced enum

public enum ErrorCode
{
    InvalidRegistration,
    NotRegistered,
    MessageTooBig,
    MissingRegistration,
    Unavailable,
    MismatchSenderId,
    InvalidDataKey,
    InvalidTtl,
    InternalServerError,
    InvalidPackageName,
    DeviceMessageRateExceeded,
    TopicsMessageRateExceeded
}

but instead, it was transformed into

public partial class Errors
{
    [JsonProperty("errorTypes")]
    public List<ErrorType> ErrorTypes { get; set; }
}

where ErrorType is as follows:

public partial class ErrorType
{
    [JsonProperty("error")]
    public string Error { get; set; }
}

which was not what I wanted.

Now, I do not know if that is the JSON is correct to yield an enum or not, but the goal remains the same.