Search code examples
c#njsonschema

NJsonSchema C# - Change Generated Value Type


I am using NJsonSchema CsharpGenerator 10.1.24 and have the below schema I am using to generate a POCO:

    "description": "schema validating people and vehicles", 
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "required": [ "oneOf" ],
    "properties": { "oneOf": [
        {
            "firstName": {"type": "string"}, 
            "lastName": {"type": "string"}, 
            "sport": {"type": "string"}
        }, 
        {
            "vehicle": {"type": "string"}, 
            "price":{"type": "number"} 
        }
     ]
   }
}

How can I get the generated C# class to have a decimal type for price instead of the default double?

public double Price { get; set;}

I tried using a custom static method with the generator settings JsonSerializerSettingsTransformationMethod property but nothing changed.


Solution

  • You can try this,

    Create CustomTypeResolver

    public class CustomTypeResolver : CSharpTypeResolver
    {
        ...
    
        public override string Resolve(JsonSchema schema, bool isNullable, string typeNameHint)
        {
            if (schema == null)
            {
                throw new ArgumentNullException(nameof(schema));
            }
    
            schema = GetResolvableSchema(schema);
    
            if (schema == ExceptionSchema)
            {
                return "System.Exception";
            }
    
            var type = schema.ActualTypeSchema.Type;
    
            if (type.HasFlag(JsonObjectType.Number))
            {
                return isNullable ? "decimal?" : "decimal"; ;
            }
    
            return base.Resolve(schema, isNullable, typeNameHint);
        }
    
        ...
    }
    

    Generate the class,

    var jsonSchema = File.ReadAllText("json1.json");
    var schema = JsonSchema.FromJsonAsync(jsonSchema).GetAwaiter().GetResult();
    var settings = new CSharpGeneratorSettings();
    var typeResolver = new CustomTypeResolver(settings);
    var generator = new CSharpGenerator(schema, settings, typeResolver);
    var code = generator.GenerateFile();