Search code examples
hotchocolate

How to change hotchocolate default json serializer


How can i change the json serializer used by hotchocalate i could not find anything in the documentation.

i tried to look at the source code but it seems like it hard coded in the HttpResponseExtensions .

its uses camel case so it will a pain to change all my models in the front side of the app , any ideas ? i think that the team is aware of this : https://github.com/ChilliCream/hotchocolate/issues/4072 but i'm looking for a workaround


Solution

  • Came across this question when looking for a way of matching cases to Models. In my case I wanted to keep casings the same for the query input and response fields.

    Got around this by adding a naming convention to override the DefaultNamingConventions:

    public class NoCaseNamingConvention : DefaultNamingConventions
    {
        public override NameString GetMemberName(MemberInfo member, MemberKind kind) {
            if (member == null)
                throw new ArgumentNullException(nameof(member));
    
            if ((kind == MemberKind.InputObjectField || kind == MemberKind.ObjectField) && member.MemberType == MemberTypes.Property)
                return member.Name;
    
            return base.GetMemberName(member, kind);
        }
    }
    

    And adding the Convention to the GraphQL:

    services.AddGraphQLServer()
        .AddConvention<INamingConventions, NoCaseNamingConvention>()
        .RegisterDbContext<ApplicationContext>(DbContextKind.Pooled)
        .AddQueryType<Query>()
        .AddProjections()
        .AddFiltering()
        .AddSorting();
    

    Also worth noting you can change the name of the top level response object in data:

    public class Query
    {
        [GraphQLName("Components")]
        [UseProjection]
        [UseFiltering]
        [UseSorting]
        public IQueryable<ComponentTable> GetComponents(ApplicationContext context) => context.Components;
    }
    

    Playground Before

    Playground After

    Hope this is helpful to folks :)