0.0.5 • Published 4 years ago
@itsquarehub/json-serialization v0.0.5
json-serialization
A typescript library for JSON object serialization.
Install
npm install @itsquarehub/json-serialization
or
yarn add @itsquarehub/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 '@itsquarehub/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 '@itsquarehub/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 '@itsquarehub/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);
}
}