4
Yes, I agree. Normally the json structure with C# works like that way. It generates class for all nested schemas.
Regards,
Pasang
3
To generate C# classes from a JSON schema, you can use the JSchemaCodeGenerator
class from the Newtonsoft.Json.Schema
NuGet package.
Here is an example of how you can use it:
Install the Newtonsoft.Json.Schema
NuGet 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.
3
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
3
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:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Name
{
[JsonProperty("$ref")]
public string @ref { get; set; }
public string title { get; set; }
public string description { get; set; }
}
public class Person
{
public string type { get; set; }
public Properties properties { get; set; }
}
public class Properties
{
public Name name { get; set; }
}
public class Root
{
public Person person { get; set; }
}
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.
3
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