Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including ts-serialize with all npm packages installed. Try it out:

require("scalts/package.json"); // scalts is a peer dependency. require("scalts-array/package.json"); // scalts-array is a peer dependency. require("ts-json-definition/package.json"); // ts-json-definition is a peer dependency. var tsSerialize = require("ts-serialize")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

ts-serialize v1.3.2

Serialization using Typescript decorators and metadata reflection

Build Status npm versionTest Coverage

ts-serialize

Serialization tool using Typescript decorators and reflect-metadata.

Usage

Example with two classes :

import {Serializable, Serialize, SerializeOpt, SerializeArray} from "ts-serialize"
 
class Role extends Serializable {
 
    // Serialize knows the primitive types
    // So it can automatically validate and convert it
    @Serialize()
    public id : string;
    
    @Serialize()
    public order : number;
}
class User extends Serializable {
 
    // You can change the property name 
    // (`id` for the class, `identifier` for the json)
    @Serialize('identifier')
    public id : string;
 
    @Serialize()
    private age : number;
    
    @Serialize()
    public language : string;
 
    // For optionals, you need to use a special decorator
    @SerializeOpt( String )
    public name : Optional< string >;
 
    // For arrays, you need to use a special decorator
    @SerializeArray( User )
    public children : User[];
 
    // Composition works naturally
    @Serialize()
    public role : Role;
    
    // You can apply your own transformers
    @Serialize(() => Math.random() * 1000)
    public random : number;
}

Now, validate you json using one of those and get either errors or your serialized object/array

static fromString< T >(str: string): Either< Error[], T >;
 
static fromStringAsArray< T >(str: string): Either< Error[], Array< T > >;
 
static fromJsObject< T >(jsObject: JsObject, jsonPath: string[] = [], classPath: string[] = []): Either< Error[], T >;
 
static fromJsArray< T >(jsArray: JsArray, jsonPath: string[] = [], classPath: string[] = []): Either< Error[], T[] >;

And convert your instances to json using :

const user = new User();
console.log(user.toJson());

Metadata

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free