1

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.

user2966445
  • 1,267
  • 16
  • 39

2 Answers2

2

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();
tontonsevilla
  • 2,649
  • 1
  • 11
  • 18
1

@tontonsevilla, How would you return both objects under oneOfs to be included in C# POCO? In example above by @user2966445 it will only generate the first item under oneOfs for me, I will only get the POCO with firstName, lastName and sport properties in the POCO & not include vehicle and price. So, when deseriazing the json to POCO it blows up if json payload contains vehicle & price.

One thing I noticed in the NJsonSchema.JsonSchema objects "Resolve" method, it also calls "RemoveNullability" method internally and this code which only returns first item in the oneOfs and not sure how to get around it.

public JsonSchema RemoveNullability( JsonSchema schema ) 
{ 
    return schema.OneOf.FirstOrDefault( ( JsonSchema o ) => !o.IsNullable( SchemaType.JsonSchema ) ) ?? schema; 
}

Maharaj
  • 313
  • 2
  • 3
  • 14