# Introduction

{% hint style="warning" %}
Note that API is on the prototype stage and can be changed drastically without backward compatibility support!
{% endhint %}

### Overview

JsonToClass (JTC) is a JavaScript library for data validation.

JTC main purpose is to ensure that expectable and received data are aligned fully. Library provides functionality for converting JS objects into class instances with syntax and semantic validation and gives full description in case of problems.&#x20;

### When to use?

JTC can be very helpful when working with data sources beyond control, like server API or local storage on client side and client request on server side.

### Example

#### Valid

```typescript
import { 
   FunctionField, JTC, NumberField, 
   ObjectArrayMeta, ObjectMeta, StringField 
} from '@taedr/jsontoclass';

class User {
   public id: number;
   public name: string;

   public sayHi() {
      console.log(`Hi! My name is ${this.name}.`);
   }
}

const USER_META = new ObjectMeta({
   builder: User,
   fields: {
      id: new NumberField(),
      name: new StringField({ minLength: 3 }),
      sayHi: new FunctionField(),
   }
});

const users = [
   { id: 1, name: `Vasya` },
   { id: 2, name: `Petya` },
   { id: 3, name: `Masha` },
];

const result = JTC.convert({
   id: `Users`,
   meta: new ObjectArrayMeta({ meta: USER_META }),
   values: users,
});

console.log(result.converted.all);

for (const user of result.converted.all) {
   user.sayHi();
}
```

#### Corrupted

```typescript
import { 
   FunctionField, JTC, NumberField, 
   ObjectArrayMeta, ObjectMeta, StringField 
} from '@taedr/jsontoclass';

class User {
   public id: number;
   public name: string;

   public sayHi() {
      console.log(`Hi! My name is ${this.name}.`);
   }
}

const USER_META = new ObjectMeta({
   builder: User,
   fields: {
      id: new NumberField(),
      name: new StringField({ minLength: 3 }),
      sayHi: new FunctionField(),
   }
});

const users = [
   { id: 1, name: `Vasya` },
   { id: `2`, name: 132 },
   null,
   { id: 3, name: `Petya` },
   { id: `3`, name: `Masha` },
   { id: 4, name: `Ib` },
];

const result = JTC.convert({
   id: `Users`,
   meta: new ObjectArrayMeta({ meta: USER_META }),
   values: users,
});

console.log(result.converted.all);
console.log(result.converted.corrupted);
console.log(result.converted.valid);

for (const user of result.converted.all) {
   user.sayHi();
}

 /*
2 -> null | Members can only be of "object" type, but got "null"
1 (EXCLUDED) -> {...} | Validation failed for all fields
1 (EXCLUDED) -> id -> 2 | Expected number, but got string
1 (EXCLUDED) -> name -> 132 | Expected string, but got number
4 (2) -> id -> 3 | Expected number, but got string
5 (3) -> name -> Ib | Length(2) is less than expected(3)
*/
console.log(JTC.log.asString(result.tree));
```
