npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

json2entity

v1.0.4

Published

This is a library to make deserializing/serializing JSON (or JS literal object) into/from TypeScript classes.

Downloads

26

Readme

json2entity


In SPA application (single page application) we use data sources are obtained from API server, usually we use it directly. This library provide simple way to transform api data to custom typescript entity class - the reverse process is also possible. In other words, we can easily carry out the serialization / deserialization process.

Installation

 npm install json2entity --save

Add to tsconfig.json

{
  "compilerOptions": {
    [...]
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    [...]
}

Run test

git clone https://github.com/lunargorge/json2entity.git
cd json2entity
npm install
npm run test

Example

Mock data.

export const personObj = {
    name: 'Rodric',
    surname: 'Brave',
    emailPrivate: {id: 1, value: '[email protected]'},
    emailBusiness: {id: 2, value: '[email protected]'},
    phones: [
        {id: 1, prefix: '+55', value: '123123123'},
        {id: 2, prefix: '+56', value: '234234234'}
    ],
    addresses: [
        {
            id: 1,
            type: 1,
            city: {
                id: 2,
                value: 'Belfaxt'
            },
            street: {
                id: 1,
                value: 'Paradise Street'
            }
        },
        {
            id: 2,
            type: 2,
            city: {
                id: 4,
                value: 'Bristol'
            },
            street: {
                id: 3,
                value: 'Broad Street'
            }
        }
    ]
};

export const personJson = JSON.stringify(personObj);

Create person.entity.ts file

import { Serializer, ArrayCollection } from 'json2entity';

import { AddressEntity } from './address.entity';
import { PhoneEntity } from './phone.entity';
import { ItemEntity } from './item.entity';

export class PersonEntity {
    @Serializer()
    public name: string;

    @Serializer()
    public surname: string;

    @Serializer({type: ItemEntity})
    public emailPrivate: ItemEntity;

    @Serializer({type: ItemEntity})
    public emailBusiness: ItemEntity;

    @Serializer({type: [PhoneEntity]})
    public phones: ArrayCollection<PhoneEntity>;

    // You can use public getter and setter.
    @Serializer({name: 'addresses', type: [AddressEntity]})
    private _addresses: ArrayCollection<AddressEntity>;

    set addresses(v: ArrayCollection<AddressEntity>) {
        this._addresses = v;
    }

    get addresses(): ArrayCollection<AddressEntity> {
        return this._addresses;
    }
}

Create item.entity.ts file

import { Serializer } from 'json2entity';

export class ItemEntity {
    @Serializer()
    public id: number;
    
    @Serializer()
    public value: string;
}

Create phone.entity.ts file

import { Serializer } from 'json2entity';

export class PhoneEntity {
    @Serializer()
    public id: number;
    
    @Serializer()
    public prefix: string;

    @Serializer()
    public value: string;
}

Create address.entity.ts file

import { Serializer } from 'json2entity';
import { ItemEntity } from './item.entity';

export class AddressEntity {
    @Serializer()
    public id: number;

    @Serializer()
    public type: number;
    
    @Serializer({type: ItemEntity})
    public city: ItemEntity;

    // You can use public getter and setter
    // source (english) street -> entity property (spanish) calle
    @Serializer({name: 'street', type: ItemEntity})
    private _calle: ItemEntity;

    set calle(v: ItemEntity) {
        this._calle = v;
    }

    get calle(): ItemEntity {
        return this._calle;
    }

}
import { Json2Entity, ArrayCollection } from 'json2entity';
import { PersonEntity } from './address.entity';

// personJson - JSON/"JS literal object"
let person: PersonEntity = (new Json2Entity()).process(personJson, new PersonEntity());

console.log('name: ' +  person.name);
console.log('surname: ' + person.surname);
console.log('emailPrivate.val: ' + person.emailPrivate.value);
console.log('emailBusiness.val: ' + person.emailBusiness.value);
console.log('phones.first().id: ' + person.phones.first().id);
console.log('phones.first().value: ' + person.phones.first().value);
console.log('phones.last().id: ' + person.phones.last().id);
console.log('phones.last().value: ' + person.phones.last().value);
console.log('phones.get(1).value: ' + person.phones.get(1).value);
console.log('addresses.first().id: ' + person.addresses.first().id);
console.log('addresses.first().calle.val: ' + person.addresses.first().calle.value);
console.log('addresses.first().city.val: ' + person.addresses.first().city.value);
console.log('addresses.last().id: ' + person.addresses.last().id);
console.log('addresses.last().calle.val: ' + person.addresses.last().calle.value);
console.log('addresses.last().city.val: ' + person.addresses.last().city.value);
console.log('addresses.get(1).id: ' + person.addresses.get(1).id);
console.log('addresses.get(1).calle.val: ' + person.addresses.get(1).calle.value);
console.log('addresses.get(1).city.val: ' + person.addresses.get(1).city.value);

Example - angular 5

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
class AppComponent implements OnInit {
    public person: PersonEntity;
    
    constructor(private http: HttpClient) {}
  
    ngOnInit(): void {
        this.http.get('<URL>').subscribe(data => {
            this.person = (new Json2Entity()).process(data, new PersonEntity());
    });
  }
}

Example - serialize/deserialize

Use data from the previous example

import { Json2Entity, Entity2Json, ArrayCollection } from 'json2entity';

// use ArrayCollection (default)
let person: PersonEntity = (new Json2Entity()).process(personJson, new PersonEntity());
let serializePerson  = (new Entity2Json()).process(person);

console.log(serializePerson);

console.log('===================');

// use Array instead ArrayCollection (In this case, also use arrays in the entities !)
let person2: PersonEntity = (new Json2Entity()).process(personJson, new PersonEntity(), true);
let serializePerson2  = (new Entity2Json()).process(person2);

console.log(serializePerson2)