To deserialize JSON into a given TypeScript type using a schema specified by an interface, you can use the TypeScript.Json.decode() function and pass in the JSON data and the TypeScript type you want to deserialize it into. You can also use the JsonSchema class from the @types/json package to create and validate JSON schemas.
Here is an example of how you can deserialize JSON into a User type using a JSON schema defined by an interface:
import { JsonSchema } from 'json';
import { User } from './user.interface';
import { TypeScriptJson } from 'typescript-json';
const json = `[
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]`;
const userSchema = new JsonSchema(User);
const result = TypeScriptJson.decode<User, any>(json, {
schema: userSchema,
});
// result is equal to
// {
// id: 1,
// name: 'Alice'
// }
In this example, the userSchema variable is created by instantiating the JsonSchema class with the User type. The decode() function is then passed the JSON data and the userSchema object as arguments, along with { schema: userSchema } option which tells the decode() function to use the userSchema to validate the json against it.
You can also validate the json against the schema before deserialization by using the JsonValidator class from the @types/json package.
import { JsonValidator } from 'json';
import { User } from './user.interface';
import { TypeScriptJson } from 'typescript-json';
const json = `[
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]`;
const userSchema = new JsonSchema(User);
const result = TypeScriptJson.decode<User, any>(json, {
schema: userSchema,
});
if(!userValidator.validateSync(json, userSchema)) {
throw new Error('JSON does not match the schema');