@peerlancers/json-serialization

A typescript library for deserializing JSON to object and serializing object to JSON.

Usage no npm install needed!

<script type="module">
  import peerlancersJsonSerialization from 'https://cdn.skypack.dev/@peerlancers/json-serialization';
</script>

README

json-serialization

A typescript library for JSON object serialization.

Install

npm install @peerlancers/json-serialization

or

yarn add @peerlancers/json-serialization

Usage

Note: Always use the JsonProperty() to decorate the property you want to serialize/deserialize, otherwise it will ignore it.

Example Model Class

export class Person {
  @JsonProperty()
  public firstName: string = undefined;

  @JsonProperty()
  public lastName: string = undefined;

  public get fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
}

Example on how to use the deserialization

import { JsonProperty, deserialize } from '@peerlancers/json-serialization';

const jsonObject: any = {
  firstName: 'John',
  lastName: 'Doe'
};

export class ApiService {
  public getPerson(): Person {
    return deserialize(Person, jsonObject);
  }
}

Example on how to use the serialization

import { serialize } from '@peerlancers/json-serialization';

const personObject: Person = new Person();
personObject.firstName = 'John';
personObject.lastName = 'Doe';

export class ApiService {

  public setPerson(): Person {
    return serialize(personObject);
  }
}

You can also set your custom deserializer or serializer and it will output based on the predicate

import { deserialize, serialize, IJsonDeserializer, IJsonSerializer } from '@peerlancers/json-serialization';

export enum Gender {
  Male = 1,
  Female = 2
}

export class GenderSerialization implements IJsonSerializer, IJsonDeserializer {
  public serialize(value: any): any {
    return `${Gender[value]}`;
  }

  public deserialize(value: any): any {
    return Gender[value];
  }
}

export class Person {
  @JsonProperty()
  public firstName: string = undefined;

  @JsonProperty({
    serializer: GenderSerialization,
    deserializer: GenderSerialization
  })
  public gender: Gender = undefined;
}

const personObject: Person = new Person();
personObject.firstName = 'John';
personObject.lastName = 'Doe';
personObject.gender = Gender.Male;

export class ApiService {

  public setPerson(): Person {
    return serialize(personObject);
  }
}

License

MIT