Hello, I searched for lots of tools to create C# class from JSON schema but none of them seems to work properly. Since I have a couple of large JSON schemas I need to automate this. But ordinary converters like json2csharp or libraries like NJsonSchema are not working (or I couldn't find how to) for a schema like this:
{
"person": {
"type": "object",
"properties": {
"name": {
"$ref": "#/definitions/name",
"title": "",
"description": ""
}
}
}
}
They all see properties as class and for example title as field. So generated classes are not proper. Do you have any suggestions?
Mahesh ChandPosted Jan 7, 2023, 4:19 AM
To generate C# classes from a JSON schema, you can use the
JSchemaCodeGeneratorclass from theNewtonsoft.Json.SchemaNuGet package.Here is an example of how you can use it:
Install the
Newtonsoft.Json.SchemaNuGet package:dotnet add package Newtonsoft.Json.Schema
Load the JSON schema file:
string schemaJson = File.ReadAllText("schema.json");
JSchema schema = JSchema.Parse(schemaJson);
Generate the C# code:
JSchemaCodeGenerationOptions options = new JSchemaCodeGenerationOptions
{
ClassName = "MyClass",
Namespace = "MyNamespace"
};
string code = JSchemaCodeGenerator.Generate(schema, options);
Save the generated code to a file:
File.WriteAllText("MyClass.cs", code);
You can then include the generated MyClass.cs file in your project and use the generated C# classes to deserialize JSON data that conforms to the schema.
Aravind GovindarajPosted Jan 6, 2023, 9:46 AM
you have one more option in VS IDE itself, paste JSON as a class.
please refer this link
https://learn.microsoft.com/en-us/visualstudio/ide/reference/paste-json-xml?view=vs-2022
Pasang TamangPosted Jan 5, 2023, 3:14 PM
Yes, I agree. Normally the json structure with C# works like that way. It generates class for all nested schemas.
Regards,
Pasang
AnilPosted Jan 5, 2023, 2:56 PM
I have already tried there. It is not converting correctly. json2csharp is good for raw JSON files, not for JSON Schemas. You can try yourself above JSON Schema. It converts like here:
The problem here, all converters see "properties" as class and. But it is just definition of fields. I can correct this small part, but my JSON Schema is large.
Pasang TamangPosted Jan 5, 2023, 2:38 PM
Hi,
Do you want to do this in your own code or some online tools is fine? I am using https://json2csharp.com online tool. You can try and see if this meets your requirement.
Regards,
Pasang