Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

camelCase: enums not honouring convention from JsonFormatter #236

Closed
davetransom opened this issue Mar 17, 2015 · 1 comment
Closed

camelCase: enums not honouring convention from JsonFormatter #236

davetransom opened this issue Mar 17, 2015 · 1 comment
Milestone

Comments

@davetransom
Copy link
Contributor

It seems enums are ignoring any serialisation settings defined by the JsonFormatter.

The Problem:
Given the following configuration:

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
json.SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true })

and enum:

public enum Fruit { Apples = 1, Oranges = 2 }   

The resulting values when serialised into the swaggger document end up as:
["Apples", "Oranges"]

instead of:
["apples", "oranges"]

Investigation:
I've looked a little further into the code base and can see a couple of things, but I wasn't sure how to go about changing them for a PR.

  1. there doesn't seem to be any JsonSerializerSettings passed into SchemaRegistry for handling serialisation of values
  2. the presence of a StringEnumConverter is checked to indicate the enum values should be serialised as a string, but the actual converter itself isn't used (perhaps due to point 1?).

Inside the CreatePrimitiveSchema method in SchemaRegistry.cs it simply outputs the enum names as defined by the assembly.

if (type.IsEnum)
{
    var converter = primitiveContract.Converter;
    var describeAsString = _describeAllEnumsAsStrings 
        || (converter != null && converter.GetType() == typeof(StringEnumConverter));

    return describeAsString
        ? new Schema { type = "string", @enum = type.GetEnumNames() }
        : new Schema { type = "integer", format = "int32", @enum = type.GetEnumValues().Cast<object>().ToArray() };
}

I did attempt to look at using reflection to call the static serialisation methods inside JSON.NET (EnumUtils.ToEnumName), but they are internal static classes, and the implementation has moved around between the dependent version (4.5.6) and the latest (6.0.8) - so it's not a good idea.

So that leaves passing in the JsonSerializerSettings so it can be used for serialising the values - but I'm not sure of the best way to handle this.

Workaround:
At present, I'm using a couple of filters to workaround it:

// config
.EnableSwaggerUi(c => 
{
    c.OperationFilter<CamelCaseEnumOperationsFilter>();
    c.SchemaFilter<CamelCaseEnumSchemaFilter>();
}

// classes
class CamelCaseEnumSchemaFilter : JsonFilterBase, ISchemaFilter
{
    public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
    {
        Modify(schema.@enum, x => camelCase((string)x));

        foreach (var prop in schema.properties)
            Modify(prop.Value.@enum, x => camelCase((string)x));
    }
}

class CamelCaseEnumOperationsFilter : JsonFilterBase, IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (null != operation.parameters)
        {
            foreach (var prop in operation.parameters)
                Modify(prop.@enum, x => camelCase((string)x));
        }
    }
}

abstract class JsonFilterBase
{
    public static void Modify<T>(IList<T> list, Func<T, T> func)
    {
        if (list == null)
            return;

        for (int i = 0; i < list.Count; ++i)
            list[i] = func(list[i]);
    }

    public static string camelCase(string s)
    {
        if (string.IsNullOrEmpty(s))
            return s;

        if (!char.IsUpper(s[0]))
            return s;

        char[] chars = s.ToCharArray();

        for (int i = 0; i < chars.Length; i++)
        {
            bool hasNext = (i + 1 < chars.Length);
            if (i > 0 && hasNext && !(char.IsUpper(chars[i + 1])  || char.IsNumber(chars[i + 1])))
                break;

            chars[i] = char.ToLowerInvariant(chars[i]);
        }

        return new string(chars);
    }
}
@domaindrivendev
Copy link
Owner

Should be resolved in latest release - 5.2.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants