Typescript Classes using JSON Schema

Typescript Classes using JSON

Today in this article, we will see how to createTypescript Classes using JSON Schema,

As we know JSON is a very popular format for information exchange, especially when dealing with information exchanges between UI and any Microservices using RESTFul principles.

We shall see how we can use NJsonSchema a C# library to create TypeScript classes easily.

Getting started

Below the article, we shall see each feature with a simple example.

Create any .NET Core application

  • Install Nuget package,

Install-Package NJsonSchema.CodeGeneration.TypeScript -Version 10.1.2

OR

Generate classes using NJsonSchema

NJsonSchema is a .NET library to read, generate and validate JSON Schema. It provides basic code generation APIs, which can be used to generate C# and TypeScript classes or Interfaces from a JSON schema.

The library reads a schema from a file or string and validates JSON data against it.

Below are a few high-level features of this library,

  • Generate C# code from JSON Schema
  • Generate TypeScript(.ts) code from JSON Schema
  • Generate JSON Schema from .json data file
  • Generate JSON Schema from .NET classes/type via reflection
  • Supports JSON Schema, Swagger, and OpenAPI DTO schemas
  • Read existing JSON Schemas and validate JSON data

Let’s use below sample Employee.json file,

  {
    "ID": "1002",
    "Name": "ABCD",
    "City": "city",
    "Country": "USA"
  }

OR

Please use below sample schema file,

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "ID": {
      "type": "string"
    },
    "Name": {
      "type": "string"
    },
    "City": {
      "type": "string"
    },
    "Country": {
      "type": "string"
    }
  },
  "required": [
    "ID",
    "Name",
    "City",
    "Country"
  ]
}

One can write the below logic to generate classes from a given JSON.

            string json = File.ReadAllText("Employee.json");
            var schemaFromFile = JsonSchema.FromSampleJson(json);
            var classGenerator = new TypeScriptGenerator(schemaFromFile);
            var codeFile = classGenerator.GenerateFile();
            File.WriteAllText("C://Test/Employee.ts", codeFile);

The generated files will be saved in the path specified above.

Below is the file generated using the above code,

export class Employee implements IEmployee {
    iD!: string;
    name!: string;
    city!: string;
    country!: string;

    constructor(data?: IEmployee) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    (<any>this)[property] = (<any>data)[property];
            }
        }
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        data["ID"] = this.iD;
        data["Name"] = this.name;
        data["City"] = this.city;
        data["Country"] = this.country;
        return data; 
    }
}

export interface IEmployee {
    iD: string;
    name: string;
    city: string;
    country: string;
}

Note:

You might get the below error due to conflicts between Newtonsfot Vs NJSonschema classes.

Unable to cast object of type 'Newtonsoft.Json.Schema.JsonSchema' to type 'NJsonSchema.JsonSchema'.

Please use the namespace below to fix the issue,

using JsonSchema = NJsonSchema.JsonSchema;

Generating Interfaces

If you need to create only Interfaces, please use TypeScriptGeneratorSettings to specify the same as below,

  var classGenerator= new TypeScriptGenerator(schemaFromFile, 
  new TypeScriptGeneratorSettings { TypeStyle = 
  TypeScriptTypeStyle.Interface });

Please see below complete code,

            string json = File.ReadAllText("Employee.json");
            var schemaFromFile = JsonSchema.FromSampleJson(json);
            var classGenerator= new TypeScriptGenerator(schemaFromFile, 
            new TypeScriptGeneratorSettings { TypeStyle = TypeScriptTypeStyle.Interface });
            var codeFile = classGenerator.GenerateFile();
            File.WriteAllText("C://Test/IEmployee.ts", codeFile);

The generated Interface IEmployee looks as below for the same Employee.json schema,

export interface IAnonymous {
    ID: string;
    Name: string;
    City: string;
    Country: string;
}

Above you need to rename IAnonymous interface to the appropriate name as required.

Happy Coding !!

Summary

Today in this article, we looked at easy techniques for creating Typescript classes and interfaces from a given JSON schema. We can use the NJsonSchema CodeGeneration .NET library to generate required typescript classes and interfaces.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.