@vsb/tson
v0.0.4
Published
[![Build Status](https://travis-ci.org/visutrb/tson.svg?branch=master)](https://travis-ci.org/visutrb/tson) [![codecov](https://codecov.io/gh/visutrb/tson/branch/master/graph/badge.svg)](https://codecov.io/gh/visutrb/tson)
Downloads
5
Maintainers
Readme
@vsb/tson
@vsb/tson is a library that makes JSON to TypeScript object conversion simpler. This library is heavily inspired by gson.
Install
- Install the package:
npm install --save @vsb/tson
- Install
reflect-metadata
:
npm install --save reflect-metadata
- 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));