DEV Community

Lorenzo Pichilli
Lorenzo Pichilli

Posted on • Originally published at itnext.io

4 1

Jackson-js: Powerful JavaScript decorators to serialize/deserialize objects into JSON and vice versa (Part 1)

Alt Text

JSON logo

After many hours of development, I finally released the first version of the jackson-js library. As the name implies, jackson-js decorators are heavily inspired by the Java annotations of the famous Java FasterXML/jackson library.

You can install it using npm install —-save jackson-js and it can be used on both client (browser) and server (Node.js) side.

Why this library? What’s the difference between using this library instead of JSON.parse and JSON.stringify?

For simple cases, you don't need this library of course, you can just use JSON.parse and JSON.stringify to serialize/deserialize JSON.

With jackson-js, you can easily manipulate your JavaScript objects/values serialization/deserialization using decorators such as @JsonProperty(), @JsonFormat(), @JsonIgnore(), and more. However, this library uses JSON.parse and JSON.stringify under the hood.

Furthermore: 

  • it not only deserialize JSON text into a JavaScript object, it also converts it into an instance of the class specified in the context option (similar packages are: class-transformer and TypedJSON); instead, with JSON.parse you will get just a simple plain (literal) JavaScript object (just Object type);
  • it supports more advanced Object concepts such as polymorphism and Object identity;
  • it supports cyclic object serialization/deserialization;
  • it supports serialization/deserialization of other native JavaScript types: Map, Set, BigInt, Typed Arrays (such as Int8Array);

This library can be useful in more complex cases, for example when you want to:

  • manipulate JSON in depth;
  • restore a JavaScript type (a similar package is class-transformer);
  • preserve type information (using polymorphic type handling decorators: @JsonTypeInfo, @JsonSubTypes, and @JsonTypeName. A similar package is TypedJSON);
  • hide some properties for certain HTTP endpoints or some other external service;
  • have different JSON response for some external application or manage different JSON data coming from other application (for example you need to communicate with a Spring Boot application that uses different JSON Schema for the same model or with other applications made with Python, PHP, etc...);
  • manage cyclic references;
  • manage other JavaScript native types such as Maps and Sets;
  • etc.

Most of the use cases of the Java FasterXML/jackson annotations are similar or equal.

In this article, I will present a basic example for each decorator.

ObjectMapper, JsonParser and JsonStringifier classes

The main classes that jackson-js offers to serialize and deserialize JavaScript objects are: ObjectMapper, JsonStringifier and JsonParser.

ObjectMapper

ObjectMapper provides functionality for both reading and writing JSON and applies jackson-js decorators. It will use instances of JsonParser and JsonStringifier for implementing actual reading/writing of JSON. It has two methods:

  • stringify(obj: T, context?: JsonStringifierContext): string: a method for serializing a JavaScript object or a value to a JSON string with decorators applied;
  • parse(text: string, context?: JsonParserContext): T: a method for deserializing a JSON string into a JavaScript object/value (of type T, based on the context given) with decorators applied.

JsonParser

JsonParser provides functionality for writing JSON and applies jackson-js decorators. The main methods are:

  • parse(text: string, context?: JsonParserContext): T : a method for deserializing a JSON string into a JavaScript object/value (of type T, based on the context given) with decorators applied;
  • transform(value: any, context?: JsonParserContext): any : a method for applying jackson-js decorators to a JavaScript object/value parsed. It returns a JavaScript object/value with decorators applied.

JsonStringifier

JsonStringifier provides functionality for reading JSON and applies jackson-js decorators. The main methods are:

  • stringify(obj: T, context?: JsonStringifierContext): string: a method for serializing a JavaScript object or a value to a JSON string with decorators applied;
  • transform(value: any, context?: JsonStringifierContext): any: a method for applying jackson-js decorators to a JavaScript object/value. It returns a JavaScript object/value with decorators applied and ready to be JSON serialized.

Decorators

Before we go on, I need to say that the most important decorators are:

  • @JsonProperty(): each class property (or its getter/setter) must be decorated with this decorator, otherwise deserialization and serialization will not work properly! That's because, for example, given a JavaScript class, there isn't any way or API (such as Reflection API for Java) to get for sure all the class properties; also because, sometimes, compilers such as TypeScript and Babel, can strip class properties after compilation from the class properties declaration;
  • @JsonClassType(): this decorator, instead, is used to define the type of a class property or method parameter. This information is used during serialization and, more important, during deserialization to know about the type of a property/parameter. This is necessary because JavaScript isn't a strongly-typed programming language, so, for example, during deserialization, without the usage of this decorator, there isn't any way to know the specific type of a class property, such as a Date or a custom Class type.

Later, they will be explained in more detail.

class Book {
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [String]})
category: string;
}
class Writer {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [Array, [Book]]})
books: Book[] = [];
}

@JsonAlias

The @JsonAlias decorator defines one or more alternative names for a property during deserialization.

API: JsonAlias - decorator options JsonAliasOptions.

import { JsonProperty, JsonClassType, JsonAlias, ObjectMapper } from 'jackson-js';
class Book {
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [String]})
@JsonAlias({values: ['bkcat', 'mybkcat']})
category: string;
}
class Writer {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [Array, [Book]]})
books: Book[] = [];
}
const objectMapper = new ObjectMapper();
// eslint-disable-next-line max-len
const jsonData = '{"id":1,"name":"John","books":[{"name":"Learning TypeScript","bkcat":"Web Development"},{"name":"Learning Spring","mybkcat":"Java"}]}';
const writer = objectMapper.parse<Writer>(jsonData, {mainCreator: () => [Writer]});
console.log(writer);
/*
Writer {
books: [
Book { name: 'Learning TypeScript', category: 'Web Development' },
Book { name: 'Learning Spring', category: 'Java' }
],
id: 1,
name: 'John'
}
*/

@JsonAnyGetter

The @JsonAnyGetter decorator allows the flexibility of using a Map or an Object Literal field as standard properties.

API: JsonAnyGetter - decorator options JsonAnyGetterOptions.

import { JsonProperty, JsonClassType, ObjectMapper, JsonAnyGetter } from 'jackson-js';
class ScreenInfo {
@JsonProperty() @JsonClassType({type: () => [String]})
id: string;
@JsonProperty() @JsonClassType({type: () => [String]})
title: string;
@JsonProperty() @JsonClassType({type: () => [Number]})
width: number;
@JsonProperty() @JsonClassType({type: () => [Number]})
height: number;
@JsonProperty() @JsonClassType({type: () => [Map, [String, Object]]})
otherInfo: Map<string, any> = new Map<string, any>();
@JsonAnyGetter()
public getOtherInfo(): Map<string, any> {
return this.otherInfo;
}
}
const objectMapper = new ObjectMapper();
const screenInfo = new ScreenInfo();
screenInfo.id = 'TradeDetails';
screenInfo.title = 'Trade Details';
screenInfo.width = 500;
screenInfo.height = 300;
screenInfo.otherInfo.set('xLocation', 400);
screenInfo.otherInfo.set('yLocation', 200);
const jsonData = objectMapper.stringify<ScreenInfo>(screenInfo);
console.log(jsonData);
// {"id":"TradeDetails","title":"Trade Details","width":500,"height":300,"xLocation":400,"yLocation":200}

@JsonAnySetter

@JsonAnySetter allows us to define a logical "any setter" mutator using a non-static two-argument method to be used as a "fallback" handler for all otherwise unrecognized properties found from JSON content.

API: JsonAnySetter - decorator options JsonAnySetterOptions.

import { JsonProperty, JsonClassType, ObjectMapper, JsonAnySetter } from 'jackson-js';
class ScreenInfo {
@JsonProperty() @JsonClassType({type: () => [String]})
id: string;
@JsonProperty() @JsonClassType({type: () => [String]})
title: string;
@JsonProperty() @JsonClassType({type: () => [Number]})
width: number;
@JsonProperty() @JsonClassType({type: () => [Number]})
height: number;
@JsonProperty() @JsonClassType({type: () => [Map, [String, Object]]})
otherInfo: Map<string, any> = new Map<string, any>();
@JsonAnySetter()
public setOtherInfo(propertyKey: string, value: any) {
this.otherInfo.set(propertyKey, value);
}
}
const jsonData = '{"id":"TradeDetails","title":"Trade Details","width":500,"height":300,"xLocation":400,"yLocation":200}';
const objectMapper = new ObjectMapper();
const screenInfo = objectMapper.parse<ScreenInfo>(jsonData, {mainCreator: () => [ScreenInfo]});
console.log(screenInfo);
/*
ScreenInfo {
otherInfo: Map(2) { 'xLocation' => 400, 'yLocation' => 200 },
id: 'TradeDetails',
title: 'Trade Details',
width: 500,
height: 300
}
*/

@JsonAppend

@JsonAppend can be used to add "virtual" properties to be written after regular properties.

API: JsonAppend - decorator options: JsonAppendOptions.

import { JsonProperty, JsonClassType, ObjectMapper, JsonAppend } from 'jackson-js';
@JsonAppend({attrs: [{
value: 'version',
}]})
class User {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
email: string;
constructor(id: number, email: string) {
this.id = id;
this.email = email;
}
}
const user = new User(1, 'john.alfa@gmail.com');
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<User>(user, {
attributes: {
version: 1.2
}
});
console.log(jsonData);
// {"id":1,"email":"john.alfa@gmail.com","version":1.2}

@JsonManagedReference and @JsonBackReference

The @JsonManagedReference and @JsonBackReference decorators can handle parent/child relationships and work around loops.

API: JsonManagedReference - decorator options JsonManagedReferenceOptions, JsonBackReference - decorator options JsonBackReferenceOptions.

import { JsonProperty, JsonClassType, ObjectMapper, JsonManagedReference, JsonBackReference } from 'jackson-js';
class User {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
email: string;
@JsonProperty() @JsonClassType({type: () => [String]})
firstname: string;
@JsonProperty() @JsonClassType({type: () => [String]})
lastname: string;
@JsonProperty() @JsonClassType({type: () => [Array, [Item]]})
@JsonManagedReference()
items: Item[] = [];
constructor(id: number, email: string, firstname: string, lastname: string) {
this.id = id;
this.email = email;
this.firstname = firstname;
this.lastname = lastname;
}
}
class Item {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [User]})
@JsonBackReference()
owner: User;
constructor(id: number, name: string, @JsonClassType({type: () => [User]}) owner: User) {
this.id = id;
this.name = name;
this.owner = owner;
}
}
const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa');
const item1 = new Item(1, 'Book', user);
const item2 = new Item(2, 'Computer', user);
user.items.push(...[item1, item2]);
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<User>(user);
console.log(jsonData);
// {"items":[{"id":1,"name":"Book"},{"id":2,"name":"Computer"}],"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}
const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]});
console.log(userParsed);
/*
<ref *1> User {
items: [
Item { id: 1, name: 'Book', owner: [Circular *1] },
Item { id: 2, name: 'Computer', owner: [Circular *1] }
],
id: 1,
email: 'john.alfa@gmail.com',
firstname: 'John',
lastname: 'Alfa'
}
*/

@JsonClassType

As said before, the @JsonClassType is used to define the type of a class property or method parameter. A type is defined as an Array of JavaScript classes, such as [Number] for properties of type number or [Array, [Number]] for properties of type Array<number> or [Map, [String, Object]] for properties of type Map<string, any>.
Why an Array of JavaScript classes? Because in this way you can map complex types such as Map<string, any> using [Map, [String, Object]] or Array<Set<any>> using [Array, [Set, [Object]]].

API: JsonClassType - decorator options JsonClassTypeOptions.

import { JsonClassType } from 'jackson-js';
class Foo2 { }
class Foo {
@JsonClassType({type: () => [Number]})
barNumber: number;
@JsonClassType({type: () => [String]})
barString: string;
@JsonClassType({type: () => [Foo2]})
barFoo2: Foo2;
@JsonClassType({type: () => [Array, [Number]]})
barNumberArray: number[] = [];
@JsonClassType({type: () => [Array, [Foo2]]})
barFoo2Array: Foo2[] = [];
@JsonClassType({type: () => [Map, [String, Foo2]]})
barMap: Map<string, Foo2> = new Map();
@JsonClassType({type: () => [Object, [String, Foo2]]})
barObjectLiteral: Record<string, Foo2> = {};
@JsonClassType({type: () => [Set, [String]]})
barSet: Set<string> = new Set();
@JsonClassType({type: () => [Array, [Set, [Foo2]]]})
barMix: Array<Set<Foo2>> = [];
}

@JsonCreator

We can use the @JsonCreator decorator to define constructors and factory methods as one to use for instantiating new instances of the associated class.
It’s very helpful when we need to deserialize some JSON that doesn’t exactly match the target entity we need to get, also with the help of the @JsonProperty decorator.

API: JsonCreator - decorator options JsonCreatorOptions.

import { JsonClassType, JsonProperty, JsonCreator, ObjectMapper } from 'jackson-js';
class Employee {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [String]})
department: string;
constructor(id: number, name: string, department: string) {
this.id = id;
this.name = name;
this.department = department;
}
@JsonCreator()
static toEmployee(id: number,
@JsonProperty({value: 'empName'}) name: string,
@JsonProperty({value: 'empDept'}) department: string): Employee {
return new Employee(id, name, department);
}
}
const jsonData = '{"id": 1,"empName": "Chris","empDept": "Admin"}';
const objectMapper = new ObjectMapper();
const employee = objectMapper.parse<Employee>(jsonData, {mainCreator: () => [Employee]});
console.log(employee);
/*
Employee {
id: 1,
name: 'Chris',
department: 'Admin'
}
*/

@JsonSerialize and @JsonDeserialize

@JsonSerialize and @JsonDeserialize are used to indicates the use of a custom serializer/deserializer.

API: JsonSerialize - decorator options JsonSerializeOptions, JsonDeserialize - decorator options JsonDeserializeOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonSerialize, JsonDeserialize } from 'jackson-js';
class DateSerializer {
static serializeDate(date, context): any {
return {
year: date.getFullYear(),
month: date.getMonth() + 1,
day: date.getDate(),
formatted: date.toLocaleDateString()
};
}
static deserializeDate(dateObj, context): Date {
return new Date(dateObj.formatted);
}
}
class Book {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [Date]})
@JsonSerialize({using: DateSerializer.serializeDate})
@JsonDeserialize({using: DateSerializer.deserializeDate})
date: Date;
constructor(id: number, name: string, @JsonClassType({type: () => [Date]}) date: Date) {
this.id = id;
this.name = name;
this.date = date;
}
}
const book = new Book(1, 'Game Of Thrones', new Date(2012, 11, 4));
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<Book>(book);
console.log(jsonData);
// {"id":1,"name":"Game Of Thrones","date":{"year":2012,"month":12,"day":4,"formatted":"4/12/2012"}}
const bookParsed = objectMapper.parse<Book>(jsonData, {mainCreator: () => [Book]});
console.log(bookParsed);
/*
Book {
id: 1,
name: 'Game Of Thrones',
date: 2012-04-11T22:00:00.000Z
}
*/

@JsonFilter

@JsonFilter can be used to indicate which logical filter is to be used for filtering out properties of type (class) decorated.

API: JsonFilter - decorator options JsonFilterOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonFilter, JsonFilterType } from 'jackson-js';
@JsonFilter({value: 'studentFilter'})
class Student {
@JsonProperty({value: 'stdName'}) @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [Number]})
age: number;
@JsonProperty() @JsonClassType({type: () => [String]})
college: string;
@JsonProperty() @JsonClassType({type: () => [String]})
city: string;
constructor(name: string, age: number, college: string, city: string) {
this.name = name;
this.age = age;
this.college = college;
this.city = city;
}
}
const student = new Student('Mohit', 30, 'ABCD', 'Varanasi');
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<Student>(student, {
filters: {
studentFilter: {
type: JsonFilterType.SERIALIZE_ALL_EXCEPT,
values: ['stdName', 'city']
}
}
});
console.log(jsonData);
// {"age":30,"college":"ABCD"}

@JsonFormat

@JsonFormat is a general-purpose decorator used for configuring details of how values of properties are to be serialized.

API: JsonFormat - decorator options JsonFormatOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonFormat, JsonFormatShape, JsonDeserialize } from 'jackson-js';
class Event {
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [Date]})
@JsonFormat({
shape: JsonFormatShape.STRING,
pattern: 'YYYY-MM-DD hh:mm:ss',
})
startDate: Date;
@JsonProperty() @JsonClassType({type: () => [Number]})
@JsonFormat({
shape: JsonFormatShape.STRING,
toFixed: 2
})
@JsonDeserialize({using: (value: string) => parseFloat(value)})
price: number;
constructor(name: string, startDate: Date, price: number) {
this.name = name;
this.startDate = startDate;
this.price = price;
}
}
const event = new Event('Event 1', new Date('2020-03-24 10:00:00'), 14.5);
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<Event>(event);
console.log(jsonData);
// {"name":"Event 1","startDate":"2020-03-24 10:00:00","price":"14.50"}

@JsonGetter and @JsonSetter

@JsonGetter and @JsonSetter are alternatives to more general @JsonProperty decorator to mark a method as a getter/setter method for a logical property.

API: JsonGetter - decorator options: JsonGetterOptions, JsonSetter - decorator options JsonSetterOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonGetter, JsonSetter } from 'jackson-js';
class User {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
firstname: string;
@JsonProperty() @JsonClassType({type: () => [String]})
lastname: string;
@JsonProperty() @JsonClassType({type: () => [Array, [String]]})
fullname: string[];
constructor(id: number, firstname: string, lastname: string) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
}
@JsonGetter() @JsonClassType({type: () => [String]})
getFullname(): string {
return this.firstname + ' ' + this.lastname;
}
@JsonSetter()
setFullname(fullname: string) {
this.fullname = fullname.split(' ');
}
}
const user = new User(1, 'John', 'Alfa');
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<User>(user);
console.log(jsonData);
// {"id":1,"firstname":"John","lastname":"Alfa","fullname":"John Alfa"}
const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]});
console.log(userParsed);
/*
User {
id: 1,
firstname: 'John',
lastname: 'Alfa',
fullname: [ 'John', 'Alfa' ]
}
*/

@JsonIdentityInfo

@JsonIdentityInfo indicates that Object Identity should be used when serializing/deserializing values - for instance, to deal with infinite recursion type of problems.

API: JsonIdentityInfo - decorator options JsonIdentityInfoOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonIdentityInfo, ObjectIdGenerator } from 'jackson-js';
@JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'User'})
class User {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
email: string;
@JsonProperty() @JsonClassType({type: () => [String]})
firstname: string;
@JsonProperty() @JsonClassType({type: () => [String]})
lastname: string;
@JsonProperty()
@JsonClassType({type: () => [Array, [Item]]})
items: Item[] = [];
constructor(id: number, email: string, firstname: string, lastname: string) {
this.id = id;
this.email = email;
this.firstname = firstname;
this.lastname = lastname;
}
}
@JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'Item'})
class Item {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty()
@JsonClassType({type: () => [User]})
owner: User;
constructor(id: number, name: string, @JsonClassType({type: () => [User]}) owner: User) {
this.id = id;
this.name = name;
this.owner = owner;
}
}
const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa');
const item1 = new Item(1, 'Book', user);
const item2 = new Item(2, 'Computer', user);
user.items.push(...[item1, item2]);
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<User>(user);
console.log(jsonData);
// {"items":[{"id":1,"name":"Book","owner":1},{"id":2,"name":"Computer","owner":1}],"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}
const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]});
console.log(userParsed);
/*
<ref *1> User {
items: [
Item { id: 1, name: 'Book', owner: [Circular *1] },
Item { id: 2, name: 'Computer', owner: [Circular *1] }
],
id: 1,
email: 'john.alfa@gmail.com',
firstname: 'John',
lastname: 'Alfa'
}
*/

@JsonIdentityReference

@JsonIdentityReference can be used for customizing details of a reference to Objects for which "Object Identity" is enabled (see @JsonIdentityInfo). The main use case is that of enforcing the use of Object Id even for the first time an Object is referenced, instead of the first instance being serialized as full Class.

API: JsonIdentityReference - decorator options JsonIdentityReferenceOptions.

@JsonIgnore, @JsonIgnoreProperties, and @JsonIgnoreType

@JsonIgnore is used to mark a property to be ignored at the field level during serialization and deserialization.

API: JsonIgnore - decorator options JsonIgnoreOptions.

@JsonIgnoreProperties can be used as a class-level decorator that marks a property or a list of properties that will be ignored during serialization and deserialization.

API: JsonIgnoreProperties - decorator options JsonIgnorePropertiesOptions.

@JsonIgnoreType indicates that all properties of decorated type are to be ignored during serialization and deserialization.

API: JsonIgnoreType - decorator options JsonIgnoreTypeOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonIgnoreType, JsonIgnoreProperties, JsonIgnore } from 'jackson-js';
@JsonIgnoreType()
class Address {
@JsonProperty() @JsonClassType({type: () => [String]})
street: string;
@JsonProperty() @JsonClassType({type: () => [String]})
city: string;
constructor(street: string, city: string) {
this.street = street;
this.city = city;
}
}
@JsonIgnoreProperties({value: ['lastname']})
class User {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonIgnore()
@JsonProperty() @JsonClassType({type: () => [String]})
firstname: string;
@JsonProperty() @JsonClassType({type: () => [String]})
lastname: string;
@JsonProperty() @JsonClassType({type: () => [Address]})
address: Address;
constructor(id: number, firstname: string, lastname: string, address: Address) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.address = address;
}
}
const address = new Address('421 Sun Ave', 'Yellow Town');
const user = new User(1, 'John', 'Alfa', address);
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<User>(user);
console.log(jsonData);
// {"id":1}
const userParsed = objectMapper.parse<User>('{"id":1,"firstname":"John","lastname":"Alfa","address":{"street":"421 Sun Ave","city":"Yellow Town"}}',
{mainCreator: () => [User]});
console.log(userParsed);
/*
User {
id: 1,
firstname: null,
lastname: null,
address: null
}
*/

@JsonInclude

@JsonInclude can be used to exclude properties with empty/null/default values.

API: JsonInclude - decorator options JsonIncludeOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonInclude, JsonIncludeType } from 'jackson-js';
@JsonInclude({value: JsonIncludeType.NON_EMPTY})
class Employee {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [String]})
dept: string;
@JsonProperty() @JsonClassType({type: () => [String]})
address: string;
@JsonProperty() @JsonClassType({type: () => [Array, [String]]})
phones: string[];
@JsonProperty() @JsonClassType({type: () => [Map, [String, String]]})
otherInfo: Map<string, string>;
constructor(id: number, name: string, dept: string, address: string, phones: string[], otherInfo: Map<string, string>) {
this.id = id;
this.name = name;
this.dept = dept;
this.address = address;
this.phones = phones;
this.otherInfo = otherInfo;
}
}
const employee = new Employee(0, 'John', '', null, [], new Map<string, string>());
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<Employee>(employee);
console.log(jsonData);
// {"id":0,"name":"John"}

@JsonInject

@JsonInject decorator is used to indicate that value of decorated property will be injected during deserialization.

API: JsonInject - decorator options JsonInjectOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonInject } from 'jackson-js';
class CurrencyRate {
@JsonProperty() @JsonClassType({type: () => [String]})
pair: string;
@JsonProperty() @JsonClassType({type: () => [Number]})
rate: number;
@JsonInject()
@JsonProperty()
@JsonClassType({type: () => [Date]})
lastUpdated: Date;
}
const objectMapper = new ObjectMapper();
const jsonData = '{"pair":"USD/JPY","rate":109.15}';
const now = new Date();
const currencyRate = objectMapper.parse<CurrencyRate>(jsonData, {
mainCreator: () => [CurrencyRate],
injectableValues: {
lastUpdated: now
}
});
console.log(currencyRate);
/*
CurrencyRate {
pair: 'USD/JPY',
rate: 109.15,
lastUpdated: 2020-05-04T20:44:15.639Z
}
*/

@JsonNaming

@JsonNaming decorator is used to choose the naming strategies (SNAKE_CASE, UPPER_CAMEL_CASE, LOWER_CAMEL_CASE, LOWER_CASE, KEBAB_CASE, and LOWER_DOT_CASE) for properties in serialization, overriding the default.

API: JsonNaming - decorator options JsonNamingOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonNaming, PropertyNamingStrategy } from 'jackson-js';
@JsonNaming({strategy: PropertyNamingStrategy.SNAKE_CASE})
class Book {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
bookName: string;
@JsonProperty() @JsonClassType({type: () => [String]})
bookCategory: string;
constructor(id: number, name: string, category: string) {
this.id = id;
this.bookName = name;
this.bookCategory = category;
}
}
const book = new Book(1, 'Learning TypeScript', 'Web Development');
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<Book>(book);
console.log(jsonData);
// {"id":1,"book_name":"Learning TypeScript","book_category":"Web Development"}

@JsonProperty

@JsonProperty can be used to define a non-static method as a "setter" or "getter" for a logical property or non-static object field to be used (serialized, deserialized) as a logical property.

API: JsonProperty - decorator options JsonPropertyOptions.

import { JsonClassType, JsonProperty, ObjectMapper } from 'jackson-js';
class Employee {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty({value: 'empName'}) @JsonClassType({type: () => [String]})
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
const employee = new Employee(1, 'John');
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<Employee>(employee);
console.log(jsonData);
// {"id":1,"empName":"John"}

@JsonPropertyOrder

@JsonPropertyOrder can be used to specify the order of properties on serialization.

API: JsonPropertyOrder - decorator options JsonPropertyOrderOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonPropertyOrder } from 'jackson-js';
@JsonPropertyOrder({value: ['email', 'id', 'name']})
class User {
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [String]})
email: string;
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
constructor(id: number, email: string, name: string) {
this.id = id;
this.email = email;
this.name = name;
}
}
const user = new User(1, 'john.alfa@gmail.com', 'John Alfa');
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<User>(user);
console.log(jsonData);
// {"email":"john.alfa@gmail.com","id":1,"name":"John Alfa"}

@JsonRawValue

@JsonRawValue decorator indicates that the decorated method or field should be serialized by including literal String value of the property as is, without quoting of characters. This can be useful for injecting values already serialized in JSON or passing javascript function definitions from server to a javascript client.

API: JsonRawValue - decorator options JsonRawValueOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonRawValue } from 'jackson-js';
class User {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
email: string;
@JsonProperty() @JsonClassType({type: () => [String]})
@JsonRawValue()
otherInfo: string;
constructor(id: number, email: string, otherInfo: string) {
this.id = id;
this.email = email;
this.otherInfo = otherInfo;
}
}
const user = new User(1, 'john.alfa@gmail.com', '{"other": "info 1", "another": "info 2"}');
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<User>(user);
console.log(jsonData);
// {"email":"john.alfa@gmail.com","id":1,"name":"John Alfa"}

@JsonRootName

@JsonRootName decorator is used - if wrapping is enabled - to specify the name of the root wrapper to be used.

API: JsonRootName - decorator options JsonRootNameOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonRootName } from 'jackson-js';
@JsonRootName({value: 'userRoot'})
class User {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
email: string;
constructor(id: number, email: string) {
this.id = id;
this.email = email;
}
}
const user = new User(1, 'john.alfa@gmail.com');
const objectMapper = new ObjectMapper();
objectMapper.defaultStringifierContext.features.serialization.WRAP_ROOT_VALUE = true;
objectMapper.defaultParserContext.features.deserialization.UNWRAP_ROOT_VALUE = true;
const jsonData = objectMapper.stringify<User>(user);
console.log(jsonData);
// {"userRoot":{"id":1,"email":"john.alfa@gmail.com"}}
const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]});
console.log(userParsed);
/*
User {
id: 1,
email: 'john.alfa@gmail.com'
}
*/

Polymorphic Type Handling Decorators: @JsonTypeInfo, @JsonSubTypes, and @JsonTypeName

  • @JsonTypeInfo: indicates details of what type information to include in serialization; API: JsonTypeInfo - decorator options JsonTypeInfoOptions;
  • @JsonSubTypes: indicates sub-types of the annotated type; API: JsonSubTypes - decorator options JsonSubTypesOptions;
  • @JsonTypeName: defines a logical type name to use for annotated class; API: JsonTypeName - decorator options JsonTypeNameOptions.
    import { JsonClassType, JsonProperty, ObjectMapper,
    JsonTypeInfo, JsonTypeInfoId, JsonTypeInfoAs, JsonSubTypes, JsonTypeName } from 'jackson-js';
    @JsonTypeInfo({
    use: JsonTypeInfoId.NAME,
    include: JsonTypeInfoAs.PROPERTY
    })
    @JsonSubTypes({
    types: [
    {class: () => Dog, name: 'dog'},
    {class: () => Cat, name: 'cat'},
    ]
    })
    class Animal {
    @JsonProperty() @JsonClassType({type: () => [String]})
    name: string;
    constructor(name: string) {
    this.name = name;
    }
    }
    @JsonTypeName({value: 'dog'})
    class Dog extends Animal { }
    @JsonTypeName({value: 'cat'})
    class Cat extends Animal { }
    const dog = new Dog('Arthur');
    const cat = new Cat('Merlin');
    const objectMapper = new ObjectMapper();
    const jsonData = objectMapper.stringify<Array<Animal>>([dog, cat]);
    console.log(jsonData);
    // [{"name":"Arthur","@type":"dog"},{"name":"Merlin","@type":"cat"}]
    const animals = objectMapper.parse<Array<Animal>>(jsonData, {mainCreator: () => [Array, [Animal]]});
    console.log(animals);
    /*
    [
    Dog {
    name: 'Arthur'
    },
    Cat {
    name: 'Merlin'
    }
    ]
    */

@JsonTypeId

@JsonTypeId decorator is used to indicate that the annotated property should be serialized as the type id when including polymorphic type information, rather than as a regular property. That polymorphic metadata is used during deserialization to recreate objects of the same subtypes as they were before serialization, rather than of the declared supertypes.

API: JsonTypeId - decorator options JsonTypeIdOptions.

@JsonTypeIdResolver

@JsonTypeIdResolver decorator can be used to plug a custom type identifier handler to be used for converting between JavaScript types and type id included in JSON content.

API: JsonTypeIdResolver - decorator options JsonTypeIdResolverOptions.

import { JsonClassType, JsonProperty, ObjectMapper,
JsonTypeInfo, JsonTypeInfoId, JsonTypeInfoAs, JsonTypeIdResolver } from 'jackson-js';
import { TypeIdResolver, JsonStringifierTransformerContext, JsonParserTransformerContext, ClassType } from 'jackson-js/dist/@types';
class CustomTypeIdResolver implements TypeIdResolver {
idFromValue(obj: any, options: (JsonStringifierTransformerContext | JsonParserTransformerContext)): string {
if (obj instanceof Dog) {
return 'animalDogType';
} else if (obj instanceof Cat) {
return 'animalCatType';
}
return null;
}
typeFromId(id: string, options: (JsonStringifierTransformerContext | JsonParserTransformerContext)): ClassType<Animal> {
switch (id) {
case 'animalDogType':
return Dog;
case 'animalCatType':
return Cat;
}
return null;
};
}
@JsonTypeInfo({
use: JsonTypeInfoId.NAME,
include: JsonTypeInfoAs.PROPERTY
})
@JsonTypeIdResolver({resolver: new CustomTypeIdResolver()})
class Animal {
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
constructor(name: string) {
this.name = name;
}
}
class Dog extends Animal { }
class Cat extends Animal { }
const dog = new Dog('Arthur');
const cat = new Cat('Merlin');
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<Array<Animal>>([dog, cat]);
console.log(jsonData);
// [{"name":"Arthur","@type":"animalDogType"},{"name":"Merlin","@type":"animalCatType"}]
const animals = objectMapper.parse<Array<Animal>>(jsonData, {mainCreator: () => [Array, [Animal]]});
console.log(animals);
/*
[
Dog {
name: 'Arthur'
},
Cat {
name: 'Merlin'
}
]
*/

@JsonUnwrapped

@JsonUnwrapped defines values that should be unwrapped/flattened when serialized/deserialized.

API: JsonUnwrapped - decorator options JsonUnwrappedOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonUnwrapped } from 'jackson-js';
class Name {
@JsonProperty() @JsonClassType({type: () => [String]})
first: string;
@JsonProperty() @JsonClassType({type: () => [String]})
last: string;
constructor(first: string, last: string) {
this.first = first;
this.last = last;
}
}
class User {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonUnwrapped()
@JsonProperty() @JsonClassType({type: () => [Name]})
name: Name;
// eslint-disable-next-line no-shadow
constructor(id: number, name: Name) {
this.id = id;
this.name = name;
}
}
const name = new Name('John', 'Alfa');
const user = new User(1, name);
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<User>(user);
console.log(jsonData);
// {"id":1,"first":"John","last":"Alfa"}
const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]});
console.log(userParsed);
/*
User {
id: 1,
name: Name {
first: 'John',
last: 'Alfa'
}
}
*/

@JsonValue

@JsonValue decorator indicates that the value of decorated accessor (either field or "getter" method) is to be used as the single value to serialize for the instance, instead of the usual method of collecting properties of value.

API: JsonValue - decorator options JsonValueOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonValue } from 'jackson-js';
class Company {
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty()
@JsonClassType({type: () => [Array, [Employee]]})
employees: Employee[] = [];
constructor(name: string) {
this.name = name;
}
}
class Employee {
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [Number]})
age: number;
@JsonValue()
@JsonProperty() @JsonClassType({type: () => [String]})
employeeInfo = '';
constructor(name: string, age: number) {
this.name = name;
this.age = age;
this.employeeInfo = this.name + ' - ' + this.age;
}
}
const company = new Company('Google');
const employee = new Employee('John Alfa', 25);
company.employees.push(employee);
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<Company>(company);
console.log(jsonData);
// {"employees":["John Alfa - 25"],"name":"Google"}

@JsonView

@JsonView decorator is used for indicating view(s) that the property that is defined by method or field decorated is part of. If multiple View class identifiers are included, the property will be part of all of them. It is also possible to use this decorator on classes to indicate the default view(s) for properties of the type, unless overridden by per-property decorator.

API: JsonView - decorator options JsonViewOptions.

import { JsonClassType, JsonProperty, ObjectMapper, JsonView } from 'jackson-js';
class Views {
static public = class Public {};
static internal = class Internal {};
}
@JsonView({value: () => [Views.internal]})
class User {
@JsonProperty() @JsonClassType({type: () => [Number]})
@JsonView({value: () => [Views.public]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
@JsonView({value: () => [Views.public]})
email: string;
@JsonProperty() @JsonClassType({type: () => [String]})
password: string;
@JsonProperty() @JsonClassType({type: () => [String]})
@JsonView({value: () => [Views.public]})
firstname: string;
@JsonProperty() @JsonClassType({type: () => [String]})
@JsonView({value: () => [Views.public]})
lastname: string;
@JsonProperty() @JsonClassType({type: () => [String]})
activationCode: string;
constructor(id: number, email: string, password: string, firstname: string, lastname: string, activationCode: string) {
this.id = id;
this.email = email;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
this.activationCode = activationCode;
}
}
const user = new User(1, 'john.alfa@gmail.com', 'rtJ9FrqP!rCE', 'John', 'Alfa', '75afe654-695e-11ea-bc55-0242ac130003');
const objectMapper = new ObjectMapper();
const jsonDataWithViewPublic = objectMapper.stringify<User>(user, {withViews: () => [Views.public]});
console.log(jsonDataWithViewPublic);
// {"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}
const userParsedWithViewPublic = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}', {
mainCreator: () => [User],
withViews: () => [Views.public]
});
console.log(userParsedWithViewPublic);
/*
User {
id: 1,
email: 'john.alfa@gmail.com',
password: null,
firstname: 'John',
lastname: 'Alfa',
activationCode: null
}
*/

Conclusion

In the next part ("Jackson-js: Examples for client (Angular) and server (Node.js) side (Part 2)"), I will give a simple example using jackson-js with Angular 9 for the client side and two examples for the server side: one using Node.js + Express + SQLite3 (with Sequelize 5) and another one using Node.js + LoopBack 4.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay