map json schema to c# model with NJsonSchema throws System.InvalidCastException

363 Views Asked by At

Im trying to convert really simple json schema to my c# model using nuget from this link

Im using example code from the github repo such as:

var schema = """{"$schema":"http://json-schema.org/draft-04/schema#","title":"Person","type":"object","additionalProperties":false,"required":["FirstName","LastName"],"properties":{"FirstName":{"type":"string"},"LastName":{"type":"string"}},"definitions":{}}""";
   
var generator = new CSharpGenerator(schema);
var file = generator.GenerateFile("mytest"); // on this line I got an exception
Console.WriteLine(file);
Console.ReadLine();

this is my json schema:

Notice: Im using .net 7 , you can notice that Im using tripple string in order to accept json with double quotes.

Exception that I get:

System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'NJsonSchema.JsonSchema'.'

What I did wrong here?

1

There are 1 best solutions below

1
whdi0404 On
using NJsonSchema;
using NJsonSchema.CodeGeneration.CSharp;

var schema = ...
var jsonSchema = await JsonSchema.FromJsonAsync(schema);
var generator = new CSharpGenerator(jsonSchema);
var file = generator.GenerateFile("mytest");
Console.WriteLine(file);
Console.ReadLine();