0.0.15 • Published 4 years ago

@peerlancers/json-serialization v0.0.15

Weekly downloads
16
License
MIT
Repository
github
Last release
4 years ago

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

0.0.15

4 years ago

0.0.14

4 years ago

0.0.13

5 years ago

0.0.12

5 years ago

0.0.11

5 years ago

0.0.10

5 years ago

0.0.9

5 years ago

0.0.8

5 years ago

0.0.7

5 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago