Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@upe/typedjson

upe-consulting95MIT1.1.1TypeScript support: included

Typed JSON parsing and serializing for TypeScript that preserves type information, using decorators. Parse JSON into actual class instances.

json, typescript, serializer, deserializer, typedjson

readme

build status coverage report

Insbired by John Weisz TypedJSON project.

TypedJSON

Strong-typed JSON parsing and serializing for TypeScript with decorators. Parse JSON into actual class instances. Recommended (but not required) to be used with ReflectDecorators, a prototype for an ES7 Reflection API for Decorator Metadata.

  • Parse regular JSON to typed class instances, safely
  • Seamlessly integrate into existing code with decorators, ultra-lightweight syntax

Install

yarn add @upe/typedjson
npm install --save @upe/typedjson

Use

  1. Add the @JsonObject decorator on a class
  2. Add the @JsonMember decorator on properties which should be serialized and deserialized
  3. Parse and stringify with the TypedJSON class
@JsonObject()
class Person {
    @JsonMember({type: String})
    firstName: string;

    @JsonMember({
        type: String,
        isRequired: true,
    })
    lastName: string;

    @JsonMember({elements: String})
    emails: string[];

    @JsonMember({type: Car})
    car: Car;
}

@JsonObject()
class Car {
    @JsonMember({type: String})
    modelName: string;
}

var json = {
                     firstName: "John",
                     lastName: "Doe",
                     emails: [],
                     car: { modelName: "i10" }
                 };

var person0 = TypedJSON.parse(JSON.stringify(json), Person);
var person1 = TypedJSON.deserialize(json, Person);

var personStr = TypedJSON.stringify(person0);
var personJSON = TypedJSON.serialize(person1)

person0 instanceof Person; // true
person1 instanceof Person; // true
person0.car instanceof Car; // true
personStr === JSON.stringify(json); // true

JsonObject Options

All JsonObject Options are now deprecated

JsonMember Options

interface IJsonMemberOptions<T> {
  /**
   * Sets the member name as it appears in the serialized JSON. Default value is determined from property key.
   */
  name?: string;

  /**
   * Sets the json member type. Optional if reflect metadata is available.
   */
  type?: ElementType<T>;

  /**
   * When the json member is an array, sets the type of array elements. Required for arrays.
   */
  elements?: IJsonMemberOptions<any> | ElementType<T>;

  /**
   * When set, indicates that the member must be present when deserializing a JSON string.
   */
  isRequired?: boolean;
}

Learn more about decorators in TypeScript

License

TypedJSON is licensed under the MIT License.