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

json-ts-mapper

v3.1.1

Published

Mapping tool between json and Typescript classes, inspired by java-spring

Downloads

138

Readme

JsonTsMapper

Test Coverage Dependencies Typescript LGPL3

JsonTsMapper is a small package that maps JSON objects to an instance of a TypeScript class

  • Minimalist : only one dependency
  • Create instances of classes instead of raw object
  • Format validation
  • Allow custom mapping
  • Easy to use
  • Inspired by Java way

Exemple :

import { JsonTsMapper, JsonProperty } from 'json-ts-mapper'
class MyClass{

  @JsonProperty(String)
  myValue:string;
}

// Assume that you get a json string or object from any source
const jsonString = '{ ... }';
const jsonObject = { ... };

const instance1 = JsonTsMapper.deserialize(jsonString, MyClass);
const instance2 = JsonTsMapper.deserialize(jsonObject, MyClass);

console.log(instance1); // print MyClass{ ... } instead of Object{ ... }
console.log(instance2); // print MyClass{ ... } instead of Object{ ... }

Changelog

See changelog

install

npm install json-ts-mapper --save

Configuration

The package makes use of TypeScript decorators. If not done already, please activate them in your tsconfig.json under compilerOptions as follows:

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

Usage

serialize / deserialize

import { JsonTsMapper } from 'json-ts-mapper'

// serialize can take an instance or an array of it
JsonTsMapper.serialize(instance) // => {...}
JsonTsMapper.serialize([instance1, instance2]) // => [{...},{...}]

//serializeToString is same to serialize but stringified
JsonTsMapper.serializeToString(instance); // => "{...}"

//serializeAs an object against a class definition
JsonTsMapper.serializeAs(instance, MyClass); // => {...}
JsonTsMapper.serializeAs([instance1, instance2], MyClass); // => [{...},{...}]

//serializeAsToString is same to serializeAs but stringified
JsonTsMapper.serializeAsToString(instance, MyClass); // => "{...}"

// deserialize can take json string or object, single instance or array
JsonTsMapper.deserialize("{...}", MyClass); // =>MyClass{...}
JsonTsMapper.deserialize({...}, MyClass); // =>MyClass{...}
JsonTsMapper.deserialize("[{...},{...}]", MyClass); // => [ MyClass{...}, MyClass{...} ]
JsonTsMapper.deserialize([{...},{...}], MyClass); // => [ MyClass{...}, MyClass{...} ]

JsonTsMapper.deserializeObject(json, MyClass); //=> deserialize unique object
JsonTsMapper.deserializeArray(json, MyClass); //=> deserialize an array

JsonTsMapper.isMapped(target) //=> return true if target is mapped, target can be a class or an instance

Class definition

  • Properties need to be preceeded by @JsonProperty(JsonPropertyType?, jsonPropertyName?)
  • Properties can be preceeded by
    • @Optional
    • @NotNull
    • @Converter(ConverterClass) to add a special converter for this property
import { JsonProperty, Optional, Converter, Any, NotNull} from 'json-ts-mapper';
import { DateConverter } from '...';

export class User {
  @JsonProperty(Number)
  @NotNull() // property cant be null or missing
  id:number;

  @JsonProperty(String)
  @Optional() // property is optional
  libelle:string;

  @JsonProperty(Boolean, 'valid')
  isValid:boolean; // json and class properties can have different names

  @JsonProperty([Number])
  values:number[];

  @JsonProperty(Any)
  anything:any;  

  // Assume that you have a class 'UserInfos' decorated with @JsonProperty
  @JsonProperty(UserInfos)
  infos:UserInfos;

  @JsonProperty(String)
  @Converter(DateConverter) // a custom converter used to handle special mapping
  date:Date;
}

JsonProperty :

Define name and type of expected JSON Property.

| Expected type | TypeScript type | | ------------- | --------------- | | String | string | | Number | number | | Boolean | boolean | | User | User | | Any | any | | [String] | string[] | | [Number] | number[] | | [Boolean] | boolean[] | | [User] | User[] | | [Any] | any[] |

Optional :

Allow property to be omitted or equal to undefined
Cant be used together with NotNull

NotNull :

Disallow property to be equal to null
Cant be used together with Optional

Converter :

Define a class that handle convertion between JSON and Ts property

Converter

A converter can be a class, an instance of class or an object, it must be satisfying the AbstractJsonConverter interface

import { AbstractJsonConverter } from 'json-ts-mapper';

class DateConverter extends AbstractJsonConverter<string, Date>{

  serialize(obj: Date): string{
    // serialize object to string
  }
  deserialize(obj: string): Date{
    // deserialize date string to date object
  }
}

const converter = {
   serialize(obj: Date): string{
    // serialize object to string
  },
  deserialize(obj: string): Date{
    // deserialize date string to date object
  }
}