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

@thorolf/json-ts-mapper

v2.1.2

Published

In Angular applications, everyone consumes JSON API's from an external source. Type checking and object mapping is only possible in TypeScript, but not in the JavaScript runtime. As the API may change at any point, it is important for larger projects to v

Downloads

6

Readme

JsonTsMapper

In Angular applications, everyone consumes JSON API's from an external source. Type checking and object mapping is only possible in TypeScript, but not in the JavaScript runtime. As the API may change at any point, it is important for larger projects to verify the consumed data.

JsonTsMapper is a small package containing a helper class that maps JSON objects to an instance of a TypeScript class. After compiling to JavaScript, the result will still be an instance of this class. One big advantage of this approach is, that you can also use methods of this class.

JsonTsMapper require some decorators in mapped class and a simple call :

import { JsonTsMapperService } from  '@thorolf/json-ts-mapper';

class AngularComponentOrService{
  constructor(private mapper : JsonTsMapperService)
  {}

  getData(){
    // Assume that you have a class 'MyClass' defined with required decorators
    // Assume that you get a json string or object from any source

    const jsonString = '{ ... }';
    const jsonObject = { ... };

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

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

Changelog

2.1.1

  • improve error messages for missmatch types
  • add overrideInitValues in README

2.1.0

  • Add mapping option overrideInitValues

Requireements

install

npm install @thorolf/json-ts-mapper --save

Configuration

Our 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

Class definition

In order to use the JsonTsMapper package, all you need to do is write decorators and import the package. The following things need to be done if you would like to map JSON to existing classes:

  • Classes need to be preceeded by @JsonObject
  • Properties need to be preceeded by @JsonProperty(jsonPropertyName, JsonPropertyType)
  • Properties can be preceeded by
    • @Optional
    • @CustomConverter(CustomConverterClass) to add a spécial converter for this property
import { JsonObject, JsonProperty, Optional, CustomConverter, Any, NotNull} from '@thorolf/json-ts-mapper';
import { DateConverter } from '...';

@JsonObject
@JsonObjectOptions({
  overrideInitValues : true
})
export class User {
  @JsonProperty('id', Number)
  @NotNull // property cant be null or missing
  id:number;

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

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

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

  @JsonProperty('anything', Any)
  anything:any;  

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

  @JsonProperty('date', String)
  @CustomConverter(DateConverter) // a custom converter used to handle special mapping
  date:Date;
}
  • JsonObject :

Declare an object that can be handle by json mapper

  • JsonObjectOptions :

Define mapping options

  • overrideInitValues :

    • if false (default) : if json property is undefined and class property initialized, keep initial value
    • if true : override initialized value of property, even to set it to undefined
  • 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

  • CustomConverter :

Define a class that handle convertion between JSON and Ts properties

CustomConverter

import { Context, JsonMapper } from  '@thorolf/json-ts-mapper';

class DateConverter extends AbstractJsonConverter<string, Date>{

  serialize(obj: Date, context?: Context): string{
    // serialize object to string
  }
  deserialize(obj: string, context?: Context): Date{
    // deserialize date string to date object
  }
}

In some case, we need additional information to serialize/deserialize properties.
A context object can be passed when calling serialize or deserialize method of mapper service. This context is passed to custom converters.

import { JsonTsMapperService, Context} from  '@thorolf/json-ts-mapper';

class AngularComponentOrService{
  constructor(private mapper : JsonTsMapperService)
  {}

  getData(){
    const jsonObject = { ... };

    const mappingContext:Context = {dateFormat:'yyyy-mm-dd', anotherProperty:['some','values']};

    const user = this.mapper.deserialize(jsonObject, User, mappingContext);
  }
}