0.0.4 • Published 4 years ago

@vsb/tson v0.0.4

Weekly downloads
1
License
ISC
Repository
github
Last release
4 years ago

@vsb/tson

Build Status codecov

@vsb/tson is a library that makes JSON to TypeScript object conversion simpler. This library is heavily inspired by gson.

Install

  1. Install the package:
npm install --save @vsb/tson
  1. Install reflect-metadata:
npm install --save reflect-metadata
  1. Import reflect-metadata in the entry file of your project (index.ts, for example):
import "reflect-metadata";

TypeScript configuration

These options must be enabled in tsconfig.json:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

Requirements

  • NodeJS >= 8.0.0 (tested on 8.x.x and 12.x.x)
  • TypeScript >= 3.4.2
  • reflect-metadata >= 0.1.0

Usage

Example

Defining TypeScript class:

import { Serializable, SerializedProperty } from "@vsb/tson";

@Serializable()
class Article {

  @SerializedProperty()
  id: number;

  @SerializedProperty()
  title: string;

  @SerializedProperty()
  content: string;

  @SerializedProperty()
  author: User;
}

@Serilizable()
class User {

  @SerializedProperty()
  id: number;

  @SerializedProperty("first_name")
  firstName: string;

  @SerializedProperty("last_name")
  lastName: string;

  // The options can be omitted for 
  // primitive data types (number, string, etc.)
  @SerializedProperty({ itemType: Article })
  articles: Article[];
}

Then create an instance of Tson to use the library:

import { Tson } from "@vsb/tson";

const tson = new Tson();
const article = tson.fromJson(json, Article); // Article {}

const jsonUser = tson.toJson(user); // Object {}

To convert array of objects, use Array.map function:

const articles = jsonArray.map(item => tson.fromJson(item, Article));

License

MIT