1

does anybody know a way to configure NJsonSchema to use CamelCase property naming durching code generation? I've a JSON schema with property names like message_id which lead to C# property name 'Message_id' where i.e. 'MessageId' whould be a more C#-like way.

With an attribute like '[JsonProperty("message_id"]' it would be no problem to specified the connection between the different names.

KwaXi
  • 123
  • 10

2 Answers2

0

So, you asked about code generation. I was having trouble with the schema it generated not matching what was getting sent to my Angular app. So, while this isn't exactly what you were looking for, perhaps it helps you find an answer (maybe?).

To generate the schema with the camel case property names, I'm setting the Default Property Name Handling to CamelCase, but this is using the deprecated call to set these settings directly. There should be some way to use the SerializerSettings directly, but I wasn't quite able to make that work. This isn't production code for me, so it will do.

internal class SchemaFileBuilder<T>
{
    public static void CreateSchemaFile()
    {
        CreateSchemaFile(typeof(T).Name);
    }

    public static void CreateSchemaFile(string fileName)
    {
        JsonSchemaGeneratorSettings settings = new JsonSchemaGeneratorSettings();
        settings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;

        var schema = NJsonSchema.JsonSchema.FromType<T>(settings);
        var json = schema.ToJson();

        Directory.CreateDirectory("Schemas");

        File.WriteAllText($"Schemas\\{fileName}.schema.json", json);
    }
}

I set this up as a generic function so I could pass multiple schemas in to either createSchemaFile functions. Here's are some example calls which would generate a Person.schema.json file and a Persons.schema.json file:

SchemaFileBuilder<Person>.CreateSchemaFile();
SchemaFileBuilder<Dictionary<string, Person>>.CreateSchemaFile("Persons");
Mike Sage
  • 251
  • 2
  • 8
0

As Mike Sage mentions above, using DefaultPropertyNameHandling is deprecated. The obsolete message suggests using SerializerSettings directly, instead; the following solution worked in my case.

var contractResolver = new DefaultContractResolver 
{
    NamingStrategy = new CamelCaseNamingStrategy()
};

var jsonSettings = new JsonSchemaGeneratorSettings 
{
    SerializerSettings = new JsonSerializerSettings 
    {
        ContractResolver = contractResolver
    }
};

var schema = JsonSchema.FromType(type, jsonSettings);

// Then, use the schema as required. For instance:
var schemaJson = schema.ToJson();
Wes Doyle
  • 2,199
  • 3
  • 17
  • 32