Options
All
  • Public
  • Public/Protected
  • All
Menu

Module Decorators

Index

Variables

Const JsonAlias

JsonAlias: JsonAliasDecorator = makeJacksonDecorator((o: JsonAliasOptions): JsonAliasOptions => ({enabled: true, ...o}),(options: JsonAliasOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null) {defineMetadata('JsonAlias', options, target.constructor, propertyKey);defineMetadata('JsonAlias', options, target.constructor, null, {suffix: propertyKey.toString()});}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {defineMetadata('JsonAliasParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}})

Decorator that can be used to define one or more alternative names for a property, accepted during deserialization as alternative to the official name. Has no effect during serialization where primary name is always used.

Usage example

class Book {
  @JsonProperty() @JsonClassType({type: () => [String]})
  name: string;

@JsonProperty() @JsonClassType({type: () => [String]}) @JsonAlias({values: ['bkcat', 'mybkcat']}) category: string;

constructor(name: string, category: string) { this.name = name; this.category = category; } }

Const JsonAnyGetter

JsonAnyGetter: JsonAnyGetterDecorator = makeJacksonDecorator((o: JsonAnyGetterOptions): JsonAnyGetterOptions => ({enabled: true, ...o}),(options: JsonAnyGetterOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null) {if (hasMetadata('JsonAnyGetter', target.constructor, null, {withContextGroups: options.contextGroups})) {throw new JacksonError(`Multiple 'any-getters' defined for "${target.constructor.name}".`);}if (!options.value) {if (descriptorOrParamIndex != null && typeof (descriptorOrParamIndex as TypedPropertyDescriptor<any>).value === 'function') {const methodName = propertyKey.toString();if (methodName.startsWith('get')) {options.value = methodName.substring(3);if (options.value.length > 0) {options.value = options.value.charAt(0).toLowerCase() + options.value.substring(1);}}if (!options.value) {// eslint-disable-next-line max-lenthrow new JacksonError(`Invalid usage of @JsonAnyGetter() on ${target.constructor.name}.${propertyKey.toString()}. You must either define a non-empty @JsonAnyGetter() option value or change the method name starting with "get".`);}} else {options.value = propertyKey.toString();}}defineMetadata('JsonAnyGetter', options, target.constructor);}})

Decorator that can be used to define a non-static, no-argument method to be an "any getter"; accessor for getting a set of key/value pairs, to be serialized as part of containing Class (similar to unwrapping) along with regular property values it has. This typically serves as a counterpart to "any setter" mutators (see JsonAnySetter). Note that the return type of decorated methods must be a Map or an Object Literal).

As with JsonAnySetter, only one property should be decorated with this decorator; if multiple methods are decorated, an exception may be thrown.

Usage example

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>();

  @JsonClassType({type: () => [Map, [String, Object]]})
  @JsonAnyGetter({for: 'otherInfo'})
  public getOtherInfo(): Map<string, any> {
    return this.otherInfo;
  }
}

Const JsonAnySetter

JsonAnySetter: JsonAnySetterDecorator = makeJacksonDecorator((o: JsonAnySetterOptions): JsonAnySetterOptions => ({enabled: true, ...o}),(options: JsonAnySetterOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null) {if (hasMetadata('JsonAnySetter', target.constructor, null, {withContextGroups: options.contextGroups})) {throw new JacksonError(`Multiple 'any-setters' defined for "${target.constructor.name}".`);}defineMetadata('JsonAnySetter', options, target.constructor);}})

Decorator that can be used to define a logical "any setter" mutator using non-static two-argument method (first argument name of property, second value to set) to be used as a "fallback" handler for all otherwise unrecognized properties found from JSON content.

If used, all otherwise unmapped key-value pairs from JSON Object values are added using mutator.

As with JsonAnyGetter, only one property should be decorated with this decorator; if multiple methods are decorated, an exception may be thrown.

Usage example

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 JsonAppend

JsonAppend: JsonAppendDecorator = makeJacksonDecorator((o: JsonAppendOptions): JsonAppendOptions => ({enabled: true,prepend: false,attrs: [],...o}),(options: JsonAppendOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonAppend', options, target);return target;}})

Decorator that may be used to add "virtual" properties to be written after regular properties (although ordering may be changed using both standard JsonPropertyOrder decorator, and properties of this decorator).

Usage example

@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 } });

Const JsonBackReference

JsonBackReference: JsonBackReferenceDecorator = makeJacksonDecorator((o: JsonBackReferenceOptions = {}): JsonBackReferenceOptions => ({enabled: true,value: 'defaultReference',...o}),(options: JsonBackReferenceOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null) {if (hasMetadata('JsonBackReference:' + options.value, target.constructor, null, {withContextGroups: options.contextGroups})) {// eslint-disable-next-line max-lenthrow new JacksonError(`Multiple back-reference properties with name "${options.value}" at ${target.constructor}["${propertyKey.toString()}"].'`);}if (descriptorOrParamIndex != null && typeof (descriptorOrParamIndex as TypedPropertyDescriptor<any>).value === 'function') {const methodName = propertyKey.toString();const prefix = methodName.startsWith('get') ? 'set' : 'get';const oppositePropertyKey = prefix + methodName.substring(3);const oppositeOptions: JsonBackReferenceOptions = {...options,_propertyKey: oppositePropertyKey};defineMetadata('JsonBackReference', oppositeOptions, target.constructor, oppositePropertyKey);if (prefix === 'set') {defineMetadata('JsonBackReference', oppositeOptions,target.constructor, null, {suffix: oppositeOptions.value});}} else {defineMetadata('JsonBackReference', options, target.constructor, null, {suffix: options.value});}defineMetadata('JsonBackReference', options, target.constructor, propertyKey);}})

Decorator used to indicate that associated property is part of two-way linkage between fields; and that its role is "child" (or "back") link. Value type of the property must be a Class: it can not be an Iterable or a Map. Linkage is handled such that the property decorated with this decorator is not serialized; and during deserialization, its value is set to instance that has the "managed" (forward) link (see JsonManagedReference).

All references have logical name to allow handling multiple linkages; typical case would be that where nodes have both parent/child and sibling linkages. If so, pairs of references should be named differently. It is an error for a class to have multiple back references with same name, even if types pointed are different.

Usage example

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[] = [];
}

class Item {
  @JsonProperty() @JsonClassType({type: () => [Number]})
  id: number;
  @JsonProperty() @JsonClassType({type: () => [String]})
  name: string;

  @JsonProperty()
  @JsonClassType({type: () => [User]})
  @JsonBackReference()
  owner: User;
}

Const JsonClassType

JsonClassType: JsonClassTypeDecorator = makeJacksonDecorator((o: JsonClassTypeOptions): JsonClassTypeOptions => ({enabled: true, ...o}),(options: JsonClassTypeOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {defineMetadata('JsonClassTypeParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}if (propertyKey != null) {defineMetadata('JsonClassType', options, target.constructor, propertyKey);defineMetadata('JsonClassType', options, target.constructor, null, {suffix: propertyKey.toString()});}})

Decorator used to define the type of a class property or method parameter. 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.

Usage example

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[] = [];
}

Const JsonCreator

JsonCreator: JsonCreatorDecorator = makeJacksonDecorator((o: JsonCreatorOptions = {}): JsonCreatorOptions => ({enabled: true,name: defaultCreatorName,mode: JsonCreatorMode.PROPERTIES,...o}),(options: JsonCreatorOptions, target, propertyKey, descriptorOrParamIndex) => {options._propertyKey = (options._propertyKey != null) ? options._propertyKey : 'constructor';if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex !== 'number' &&typeof descriptorOrParamIndex.value === 'function') {options._method = descriptorOrParamIndex.value;if (options.name &&hasMetadata('JsonCreator:' + options.name, target, null, {withContextGroups: options.contextGroups})) {throw new JacksonError(`Already had a @JsonCreator() with name "${options.name}" for Class "${target.name}".`);}defineMetadata('JsonCreator', options, target, null, {suffix: options.name});} else if (descriptorOrParamIndex == null && propertyKey == null) {options._ctor = target;// get original constructorwhile (options._ctor.toString().trim().startsWith('class extends target {')) {options._ctor = Object.getPrototypeOf(options._ctor);}defineMetadata('JsonCreator', options, target, null, {suffix: options.name});return target;}})

Decorator that can be used to define constructors and factory methods as one to use for instantiating new instances of the associated class.

When decorating creator methods (constructors, factory methods), method must either be:

  • Single-argument constructor/factory method without JsonProperty decorator for the argument: the whole incoming data value is passed as the argument to creator (see JsonCreatorMode.DELEGATING);
  • Constructor/factory method where every argument is bound from matching properties of incoming Object value, using creator argument names (explicit or implicit) to match incoming Object properties to arguments (see JsonCreatorMode.PROPERTIES).

Usage example

@JsonCreator()
class Employee {
  @JsonProperty() @JsonClassType({type: () => [Number]})
  id: number;
  @JsonProperty() @JsonClassType({type: () => [String]})
  name: string;
  @JsonProperty() @JsonClassType({type: () => [String]})
  department: string;

constructor(id: number, @JsonProperty({value: 'empName'}) name: string, @JsonProperty({value: 'empDept'}) department: string) { this.id = id; this.name = name; this.department = department; } }

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); }

@JsonCreator({name: 'AnotherEmployeeCreator'}) static toAnotherEmployee(id: number, @JsonProperty({value: 'anotherEmpName'}) anotherName: string, @JsonProperty({value: 'anotherEmpDept'}) anotherDepartment: string): Employee { return new Employee(id, 'Another ' + anotherName, 'Another ' + anotherDepartment); } }

Const JsonDeserialize

JsonDeserialize: JsonDeserializeDecorator = makeJacksonDecorator((o: JsonDeserializeOptions): JsonDeserializeOptions => ({enabled: true, ...o}),(options: JsonDeserializeOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonDeserialize', options, target);return target;}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {defineMetadata('JsonDeserializeParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}if (propertyKey != null) {defineMetadata('JsonDeserialize', options, target.constructor, propertyKey);}})

Decorator used to indicates the use of a custom deserializer.

Usage example

class DateSerializer {
  static serializeDate(date): any {
    return {
      year: date.getFullYear(),
      month: date.getMonth() + 1,
      day: date.getDate(),
      formatted: date.toLocaleDateString()
    };
  }
  static deserializeDate(dateObj): Date {
    return new Date(dateObj.formatted);
  }
}

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

@JsonProperty() @JsonSerialize({using: DateSerializer.serializeDate}) @JsonDeserialize({using: DateSerializer.deserializeDate}) @JsonClassType({type: () => [Date]}) date: Date; }

Const JsonFilter

JsonFilter: JsonFilterDecorator = makeJacksonDecorator((o: JsonFilterOptions): JsonFilterOptions => ({enabled: true, ...o }),(options: JsonFilterOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonFilter', options, target);return target;}if (propertyKey != null) {defineMetadata('JsonFilter', options, target.constructor, propertyKey);}})

Decorator used to indicate which logical filter is to be used for filtering out properties of type (class) decorated. Association made by this decorator declaring ids of filters, and JsonStringifierContext providing matching filters by id.

When used for properties (fields, methods), this decorator applies to values: so when applied to Iterables and Maps, it will apply to contained values, not the container.

Usage example

@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']
    }
  }
});

Const JsonFormat

JsonFormat: JsonFormatDecorator = makeJacksonDecorator((o: JsonFormatOptions): JsonFormatOptions => ({enabled: true,shape: JsonFormatShape.ANY,// @ts-ignorelocale: 'en',...o}),(options: JsonFormatOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonFormat', options, target);return target;}if (propertyKey != null) {defineMetadata('JsonFormat', options, target.constructor, propertyKey);}})

General-purpose decorator used for configuring details of how values of properties are to be serialized. This decorator does not have specific universal interpretation: instead, effect depends on datatype of property being decorated.

Iterables, such as Array and Set, can be serialized as JSON Objects if JsonFormatShape.OBJECT is used.

IMPORTANT NOTE: To be able to use JsonFormat on class properties of type Date with JsonFormatShape.STRING, a date library needs to be set. Date libraries supported: https://github.com/moment/moment, https://github.com/iamkun/dayjs/.

Usage example

class Event {
  @JsonProperty() @JsonClassType({type: () => [String]})
  name: string;

  @JsonProperty()
  @JsonFormat({
    shape: JsonFormatShape.STRING,
    pattern: 'YYYY-MM-DD hh:mm:ss',
  })
  @JsonClassType({type: () => [Date]})
  startDate: Date;

  @JsonProperty() @JsonClassType({type: () => [Number]})
  @JsonFormat({
    shape: JsonFormatShape.STRING,
    toFixed: 2
  })
  @JsonDeserialize({using: (value: string) => parseFloat(value)})
  price: number;

  @JsonProperty() @JsonClassType({type: () => [Number]})
  @JsonFormat({
    shape: JsonFormatShape.BOOLEAN
  })
  @JsonDeserialize({using: (value: boolean) => value ? 1 : 0})
  canceled: number;

  @JsonProperty() @JsonClassType({type: () => [Object, [String, String]]})
  @JsonFormat({
    shape: JsonFormatShape.ARRAY
  })
  @JsonDeserialize({
    using: (value: string[]) => ({
      address: value[0],
      phone: value[1]
    })
  })
  info: {
    address: string;
    phone: string;
  };
}

Const JsonGetter

JsonGetter: JsonGetterDecorator = makeJacksonDecorator((o: JsonGetterOptions): JsonGetterOptions => ({enabled: true, ...o}),(options: JsonGetterOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null) {if (!options.value) {if (descriptorOrParamIndex != null && typeof (descriptorOrParamIndex as TypedPropertyDescriptor<any>).value === 'function') {const methodName = propertyKey.toString();if (methodName.startsWith('get')) {options.value = methodName.substring(3);if (options.value.length > 0) {options.value = options.value.charAt(0).toLowerCase() + options.value.substring(1);}}if (!options.value) {// eslint-disable-next-line max-lenthrow new JacksonError(`Invalid usage of @JsonGetter() on ${target.constructor.name}.${propertyKey.toString()}. You must either define a non-empty @JsonGetter() option value or change the method name starting with "get".`);}} else {options.value = propertyKey.toString();}}defineMetadata('JsonGetter', options, target.constructor, propertyKey);defineMetadata('JsonVirtualProperty', options, target.constructor, null, {suffix: propertyKey.toString()});}})

Decorator that can be used to define a non-static, no-argument value-returning (non-void) method to be used as a "getter" for a logical property. It can be used as an alternative to more general JsonProperty decorator (which is the recommended choice in general case).

Getter means that when serializing Object instance of class that has this method (possibly inherited from a super class), a call is made through the method, and return value will be serialized as value of the property.

Usage example

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[];

  @JsonGetter() @JsonClassType({type: () => [String]})
  getFullname(): string {
    return this.firstname + ' ' + this.lastname;
  }

  @JsonSetter()
  setFullname(fullname: string) {
    this.fullname = fullname.split(' ');
  }
}

Const JsonIdentityInfo

JsonIdentityInfo: JsonIdentityInfoDecorator = makeJacksonDecorator((o: JsonIdentityInfoOptions): JsonIdentityInfoOptions => ({enabled: true,property: '@id',uuidv5: {},uuidv4: {},uuidv3: {},uuidv1: {},...o}),(options: JsonIdentityInfoOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonIdentityInfo', options, target);return target;}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {defineMetadata('JsonIdentityInfoParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}if (propertyKey != null) {defineMetadata('JsonIdentityInfo', options, target.constructor, propertyKey);}})

Decorator used for indicating that values of decorated type or property should be serializing so that instances either contain additional object identifier (in addition actual object properties), or as a reference that consists of an object id that refers to a full serialization. In practice this is done by serializing the first instance as full object and object identity, and other references to the object as reference values.

IMPORTANT NOTE: To be able to use JsonIdentityInfo with any UUID ObjectIdGenerator, an UUID library needs to be set. UUID libraries supported: https://github.com/uuidjs/uuid.

Usage example

@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[] = [];
}

@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;
}

Const JsonIdentityReference

JsonIdentityReference: JsonIdentityReferenceDecorator = makeJacksonDecorator((o: JsonIdentityReferenceOptions): JsonIdentityReferenceOptions => ({enabled: true,...o}),(options: JsonIdentityReferenceOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonIdentityReference', options, target);return target;}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {defineMetadata('JsonIdentityReferenceParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}if (propertyKey != null) {defineMetadata('JsonIdentityReference', options, target.constructor, propertyKey);}})

Decorator that 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 use of Object Id even for the first time an Object is referenced, instead of first instance being serialized as full Class.

Usage example

@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[] = []; }

@JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'Item'}) @JsonIdentityReference({alwaysAsId: true}) class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string;

@JsonProperty() @JsonClassType({type: () => [User]}) owner: User; }

Const JsonIgnore

JsonIgnore: JsonIgnoreDecorator = makeJacksonDecorator((o: JsonIgnoreOptions): JsonIgnoreOptions => ({enabled: true, ...o}),(options: JsonIgnoreOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null) {defineMetadata('JsonIgnore', options, target.constructor, propertyKey);}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {defineMetadata('JsonIgnoreParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}})

Decorator that indicates that the logical property that the accessor (field, getter/setter method or Creator parameter [of JsonCreator-decorated constructor or factory method]) is to be ignored during serialization and deserialization functionality.

Usage example

class Item {
  @JsonProperty() @JsonClassType({type: () => [Number]})
  id: number;
  @JsonProperty() @JsonClassType({type: () => [String]})
  name: string;

@JsonProperty() @JsonClassType({type: () => [String]}) @JsonIgnore() category: string; }

Const JsonIgnoreProperties

JsonIgnoreProperties: JsonIgnorePropertiesDecorator = makeJacksonDecorator((o: JsonIgnorePropertiesOptions): JsonIgnorePropertiesOptions => ({enabled: true,allowGetters: false,allowSetters: false,ignoreUnknown: false,value: [],...o}),(options: JsonIgnorePropertiesOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonIgnoreProperties', options, target);return target;}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {defineMetadata('JsonIgnorePropertiesParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}if (propertyKey != null) {defineMetadata('JsonIgnoreProperties', options, target.constructor, propertyKey);}})

Decorator that can be used to either suppress serialization of properties (during serialization), or ignore processing of JSON properties read (during deserialization).

When used for properties (fields, methods), this decorator applies to values: so when applied to Iterables and Maps, it will apply to contained values, not the container.

Usage example

@JsonIgnoreProperties({
  value: ['firstname', 'lastname']
})
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;
}

Const JsonIgnoreType

JsonIgnoreType: JsonIgnoreTypeDecorator = makeJacksonDecorator((o: JsonIgnoreTypeOptions): JsonIgnoreTypeOptions => ({enabled: true, ...o}),(options: JsonIgnoreTypeOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonIgnoreType', options, target);return target;}})

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

Usage example

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[] = []; }

@JsonIgnoreType() class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [String]}) category: string;

@JsonProperty() @JsonClassType({type: () => [User]}) owner: User; }

Const JsonInclude

JsonInclude: JsonIncludeDecorator = makeJacksonDecorator((o: JsonIncludeOptions): JsonIncludeOptions => ({enabled: true,value: JsonIncludeType.ALWAYS,...o}),(options: JsonIncludeOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonInclude', options, target);return target;}if (propertyKey != null) {defineMetadata('JsonInclude', options, target.constructor, propertyKey);}})

Decorator used to indicate when value of the decorated property or all properties of the decorated class, is to be serialized. Without decorator property values are always included, but by using this decorator one can specify simple exclusion rules to reduce amount of properties to write out.

Note that the main inclusion criteria is checked on JavaScript object level, for the decorated type, and NOT on JSON output. So, even with JsonIncludeType.NON_NULL it is possible that JSON null values are output, if object reference in question is not null.

Usage example

@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>;
}

Const JsonInject

JsonInject: JsonInjectDecorator = makeJacksonDecorator((o: JsonInjectOptions = {}): JsonInjectOptions => ({enabled: true,useInput: true,...o}),(options: JsonInjectOptions, target, propertyKey, descriptorOrParamIndex) => {if (!options.value && propertyKey != null) {options.value = propertyKey.toString();}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {if (!options.value || (propertyKey != null && options.value === propertyKey.toString())) {const method = (propertyKey) ? target[propertyKey.toString()] : target;const argNames = getArgumentNames(method);options.value = argNames[descriptorOrParamIndex];}defineMetadata('JsonInjectParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}if (propertyKey != null) {if (descriptorOrParamIndex != null && typeof (descriptorOrParamIndex as TypedPropertyDescriptor<any>).value === 'function') {const methodName = propertyKey.toString();if (methodName.startsWith('get') || methodName.startsWith('set')) {options.value = methodName.substring(3);if (options.value.length > 0) {options.value = options.value.charAt(0).toLowerCase() + options.value.substring(1);}}if (!options.value) {// eslint-disable-next-line max-lenthrow new JacksonError(`Invalid usage of @JsonInject() on ${((target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor).name}.${propertyKey.toString()}. You must either define a non-empty @JsonInject() option value or change the method name starting with "get" for Getters or "set" for Setters.`);}}defineMetadata('JsonInject', options, target.constructor, propertyKey);}})

Decorator used for indicating that value of decorated property will be "injected" through JsonParserContext.injectableValues value.

Usage example

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 } });

Const JsonManagedReference

JsonManagedReference: JsonManagedReferenceDecorator = makeJacksonDecorator((o: JsonManagedReferenceOptions = {}): JsonManagedReferenceOptions => ({enabled: true,value: 'defaultReference',...o}),(options: JsonManagedReferenceOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null) {if (hasMetadata('JsonManagedReference:' + options.value, target.constructor, null, {withContextGroups: options.contextGroups})) {// eslint-disable-next-line max-lenthrow new JacksonError(`Multiple managed-reference properties with name "${options.value}" at ${target.constructor}["${propertyKey.toString()}"].'`);}if (descriptorOrParamIndex != null && typeof (descriptorOrParamIndex as TypedPropertyDescriptor<any>).value === 'function') {const methodName = propertyKey.toString();const prefix = methodName.startsWith('get') ? 'set' : 'get';const oppositePropertyKey = prefix + methodName.substring(3);const oppositeOptions: JsonManagedReferenceOptions = {...options,_propertyKey: oppositePropertyKey};defineMetadata('JsonManagedReference', oppositeOptions, target.constructor, oppositePropertyKey);}defineMetadata('JsonManagedReference', options, target.constructor, propertyKey);}})

Decorator used to indicate that decorated property is part of two-way linkage between fields and that its role is "parent" (or "forward") link. Value type (class) of property must have a single compatible property decorated with JsonBackReference. Linkage is handled such that the property decorated with this decorator is handled normally (serialized normally, no special handling for deserialization); it is the matching back reference that requires special handling.

All references have logical name to allow handling multiple linkages; typical case would be that where nodes have both parent/child and sibling linkages. If so, pairs of references should be named differently. It is an error for a class too have multiple managed references with same name, even if types pointed are different.

Usage example

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[] = [];
}

class Item {
  @JsonProperty() @JsonClassType({type: () => [Number]})
  id: number;
  @JsonProperty() @JsonClassType({type: () => [String]})
  name: string;

  @JsonProperty()
  @JsonClassType({type: () => [User]})
  @JsonBackReference()
  owner: User;
}

Const JsonNaming

JsonNaming: JsonNamingDecorator = makeJacksonDecorator((o: JsonNamingOptions): JsonNamingOptions => ({enabled: true,...o}),(options: JsonNamingOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonNaming', options, target);return target;}})

Decorator that can be used to indicate a PropertyNamingStrategy to use for decorated class.

Usage example

@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 JsonProperty

JsonProperty: JsonPropertyDecorator = makeJacksonDecorator((o: JsonPropertyOptions = {}): JsonPropertyOptions => ({enabled: true,required: false,access: JsonPropertyAccess.READ_WRITE,...o}),(options: JsonPropertyOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null && !options.value) {if (descriptorOrParamIndex != null && typeof (descriptorOrParamIndex as TypedPropertyDescriptor<any>).value === 'function') {const methodName = propertyKey.toString();if (methodName.startsWith('get') || methodName.startsWith('set')) {options.value = methodName.substring(3);if (options.value.length > 0) {options.value = options.value.charAt(0).toLowerCase() + options.value.substring(1);}}if (!options.value) {// eslint-disable-next-line max-lenthrow new JacksonError(`Invalid usage of @JsonProperty() on ${((target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor).name}.${propertyKey.toString()}. You must either define a non-empty @JsonProperty() option value or change the method name starting with "get" for Getters or "set" for Setters.`);}} else {options.value = propertyKey.toString();}}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {if (!options.value || (propertyKey != null && options.value === propertyKey.toString())) {const method = (propertyKey) ? target[propertyKey.toString()] : target;const argNames = getArgumentNames(method);options.value = argNames[descriptorOrParamIndex];}defineMetadata('JsonPropertyParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}if (propertyKey != null) {defineMetadata('JsonProperty', options, target.constructor, propertyKey);defineMetadata('JsonProperty', options, target.constructor, null, {suffix: propertyKey.toString()});defineMetadata('JsonVirtualProperty', options, target.constructor, null, {suffix: propertyKey.toString()});}})

Decorator that can be used to define a non-static method as a "setter" or "getter" for a logical property (depending on its signature: starting with "get" for Getters and "set" for Setters), or non-static object field to be used (serialized, deserialized) as a logical property.

If no option value is defined, then the field name is used as the property name without any modifications, but it can be specified to non-empty value to specify different name. Property name refers to name used externally, as the field name in JSON objects.

IMPORTANT: 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 - https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/package-summary.html) to get all the class properties and its types (see JsonClassType).

Usage example

class User {
  @JsonProperty() @JsonClassType({type: () => [Number]})
  id: number;
  @JsonProperty() @JsonClassType({type: () => [String]})
  firstname: string;
  @JsonProperty() @JsonClassType({type: () => [String]})
  lastname: string;

  @JsonProperty() @JsonClassType({type: () => [String]})
  getFullname(): string {
    return this.firstname + ' ' + this.lastname;
  }

  @JsonProperty()
  setFullname(fullname: string) {
    const fullnameSplitted = fullname.split(' ');
    this.firstname = fullnameSplitted[0];
    this.lastname = fullnameSplitted[0];
  }
}

Const JsonPropertyOrder

JsonPropertyOrder: JsonPropertyOrderDecorator = makeJacksonDecorator((o: JsonPropertyOrderOptions): JsonPropertyOrderOptions => ({enabled: true,alphabetic: false,value: [],...o}),(options: JsonPropertyOrderOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonPropertyOrder', options, target);return target;}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {defineMetadata('JsonPropertyOrderParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}if (propertyKey != null) {defineMetadata('JsonPropertyOrder', options, target.constructor, propertyKey);}})

Decorator that can be used to define ordering (possibly partial) to use when serializing object properties. Properties included in decorator declaration will be serialized first (in defined order), followed by any properties not included in the definition. This decorator definition will override any implicit orderings.

When used for properties (fields, methods), this decorator applies to values: so when applied to Iterables and Maps, it will apply to contained values, not the container.

Usage example

@JsonPropertyOrder({value: ['email', 'lastname']})
class User {
  @JsonProperty() @JsonClassType({type: () => [String]})
  email: string;
  @JsonProperty() @JsonClassType({type: () => [Number]})
  id: number;
  @JsonProperty() @JsonClassType({type: () => [String]})
  firstname: string;
  @JsonProperty() @JsonClassType({type: () => [String]})
  lastname: string;
}

Const JsonRawValue

JsonRawValue: JsonRawValueDecorator = makeJacksonDecorator((o: JsonRawValueOptions): JsonRawValueOptions => ({enabled: true, ...o}),(options: JsonRawValueOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null) {defineMetadata('JsonRawValue', options, target.constructor, propertyKey);}})

Decorator that 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.

Warning: the resulting JSON stream may be invalid depending on your input value.

Usage example

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);

Const JsonRootName

JsonRootName: JsonRootNameDecorator = makeJacksonDecorator((o: JsonRootNameOptions = {}): JsonRootNameOptions => ({enabled: true, ...o}),(options: JsonRootNameOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {options.value = (options.value == null) ? (target as ObjectConstructor).name : options.value;defineMetadata('JsonRootName', options, target);return target;}})

Decorator used to indicate name to use for root-level wrapping, if wrapping is enabled (see SerializationFeature.WRAP_ROOT_VALUE and DeserializationFeature.UNWRAP_ROOT_VALUE). Decorator itself does not indicate that wrapping should be used; but if it is, name used for serialization should be name specified here, and deserializer will expect the name as well.

Usage example

@JsonRootName()
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.features.serialization.WRAP_ROOT_VALUE = true; objectMapper.features.deserialization.UNWRAP_ROOT_VALUE = true;

const jsonData = objectMapper.stringify<User>(user);

const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]});

Const JsonSerialize

JsonSerialize: JsonSerializeDecorator = makeJacksonDecorator((o: JsonSerializeOptions): JsonSerializeOptions => ({enabled: true, ...o}),(options: JsonSerializeOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonSerialize', options, target);return target;}if (propertyKey != null) {defineMetadata('JsonSerialize', options, target.constructor, propertyKey);}})

Decorator used to indicates the use of a custom serializer.

Usage example

class DateSerializer {
  static serializeDate(date): any {
    return {
      year: date.getFullYear(),
      month: date.getMonth() + 1,
      day: date.getDate(),
      formatted: date.toLocaleDateString()
    };
  }
  static deserializeDate(dateObj): Date {
    return new Date(dateObj.formatted);
  }
}

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

@JsonProperty() @JsonSerialize({using: DateSerializer.serializeDate}) @JsonDeserialize({using: DateSerializer.deserializeDate}) @JsonClassType({type: () => [Date]}) date: Date; }

Const JsonSetter

JsonSetter: JsonSetterDecorator = makeJacksonDecorator((o: JsonSetterOptions): JsonSetterOptions => ({enabled: true,nulls: JsonSetterNulls.SET,contentNulls: JsonSetterNulls.SET,...o}),(options: JsonSetterOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null) {if (!options.value) {if (descriptorOrParamIndex != null && typeof (descriptorOrParamIndex as TypedPropertyDescriptor<any>).value === 'function') {const methodName = propertyKey.toString();if (methodName.startsWith('set')) {options.value = methodName.substring(3);if (options.value.length > 0) {options.value = options.value.charAt(0).toLowerCase() + options.value.substring(1);}}if (!options.value) {// eslint-disable-next-line max-lenthrow new JacksonError(`Invalid usage of @JsonSetter() on ${target.constructor.name}.${propertyKey.toString()}. You must either define a non-empty @JsonSetter() option value or change the method name starting with "set".`);}} else {options.value = propertyKey.toString();}}defineMetadata('JsonSetter', options, target.constructor, propertyKey);defineMetadata('JsonVirtualProperty', options, target.constructor, null, {suffix: propertyKey.toString()});}})

Decorator that can be used to define a non-static, single-argument method to be used as a "setter" for a logical property as an alternative to recommended JsonProperty decorator.

Setter means that when deserializing Object instance of class that has this method (possibly inherited from a super class), a call is made through the method.

Usage example

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[];

  @JsonGetter() @JsonClassType({type: () => [String]})
  getFullname(): string {
    return this.firstname + ' ' + this.lastname;
  }

  @JsonSetter()
  setFullname(fullname: string) {
    this.fullname = fullname.split(' ');
  }
}

Const JsonSubTypes

JsonSubTypes: JsonSubTypesDecorator = makeJacksonDecorator((o: JsonSubTypesOptions): JsonSubTypesOptions => ({enabled: true, ...o}),(options: JsonSubTypesOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonSubTypes', options, target);return target;}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {defineMetadata('JsonSubTypesParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}if (propertyKey != null) {defineMetadata('JsonSubTypes', options, target.constructor, propertyKey);}})

Decorator used with JsonTypeInfo to indicate sub-types of serializable polymorphic types, and to associate logical names used within JSON content.

Note that just decorating a property or base type with this decorator does NOT enable polymorphic type handling: in addition, JsonTypeInfo decorator is needed, and only in such case is subtype information used.

Usage example

@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;
}

@JsonTypeName({value: 'dog'})
class Dog extends Animal {

}

@JsonTypeName({value: 'cat'})
class Cat extends Animal {

}

Const JsonTypeId

JsonTypeId: JsonTypeIdDecorator = makeJacksonDecorator((o: JsonTypeIdOptions = {}): JsonTypeIdOptions => ({enabled: true, ...o}),(options: JsonTypeIdOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null) {defineMetadata('JsonTypeId', options, target.constructor);}})

Decorator that can be used on a property accessor (field, getter or setter, constructor parameter) to indicate that the property is to contain type id to use when including polymorphic type information. This decorator should only be used if the intent is to override generation of standard type id: if so, value of the property will be accessed during serialization and used as the type id.

On deserialization, this decorator has no effect.

On serialization, this decorator will exclude property from being serialized along other properties; instead, its value is serialized as the type identifier.

Usage example

@JsonTypeInfo({
  use: JsonTypeInfoId.NAME,
  include: JsonTypeInfoAs.WRAPPER_OBJECT
})
@JsonSubTypes({
  types: [
    {class: () => Dog, name: 'dog'},
    {class: () => Cat, name: 'cat'},
  ]
})
class Animal {
  @JsonProperty() @JsonClassType({type: () => [String]})
  name: string;
}

@JsonTypeName({value: 'dog'})
class Dog extends Animal {
  @JsonTypeId() @JsonClassType({type: () => [String]})
  typeId: string;
}

@JsonTypeName({value: 'cat'})
class Cat extends Animal {
  @JsonTypeId() @JsonClassType({type: () => [String]})
  getTypeId(): string {
    return 'CatTypeId';
  }
}

Const JsonTypeIdResolver

JsonTypeIdResolver: JsonTypeIdResolverDecorator = makeJacksonDecorator((o: JsonTypeIdResolverOptions): JsonTypeIdResolverOptions => ({enabled: true, ...o}),(options: JsonTypeIdResolverOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonTypeIdResolver', options, target);return target;}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {defineMetadata('JsonTypeIdResolverParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}if (propertyKey != null) {defineMetadata('JsonTypeIdResolver', options, target.constructor, propertyKey);}})

Decorator that can be used to plug a custom type identifier handler (TypeIdResolver) to be used for converting between JavaScript types and type id included in JSON content. In simplest cases this can be a simple class with static mapping between type names and matching classes.

Usage example

class CustomTypeIdResolver implements TypeIdResolver {
  idFromValue(obj: any, context: (JsonStringifierTransformerContext | JsonParserTransformerContext)): string {
    if (obj instanceof Dog) {
      return 'animalDogType';
    } else if (obj instanceof Cat) {
      return 'animalCatType';
    }
    return null;
  }
  typeFromId(id: string, context: (JsonStringifierTransformerContext | JsonParserTransformerContext)): ClassType<any> {
    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; }

class Dog extends Animal {

}

class Cat extends Animal {

}

Const JsonTypeInfo

JsonTypeInfo: JsonTypeInfoDecorator = makeJacksonDecorator((o: JsonTypeInfoOptions): JsonTypeInfoOptions => ({enabled: true,use: JsonTypeInfoId.NAME,include: JsonTypeInfoAs.PROPERTY,property: '@type',...o}),(options: JsonTypeInfoOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonTypeInfo', options, target);return target;}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {defineMetadata('JsonTypeInfoParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}if (propertyKey != null) {defineMetadata('JsonTypeInfo', options, target.constructor, propertyKey);}})

Decorator used for configuring details of if and how type information is used with JSON serialization and deserialization, to preserve information about actual class of Object instances. This is necessarily for polymorphic types, and may also be needed to link abstract declared types and matching concrete implementation.

When used for properties (fields, methods), this decorator applies to values: so when applied to Iterables and Maps, it will apply to contained values, not the container.

Usage example

@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;
}

@JsonTypeName({value: 'dog'})
class Dog extends Animal {

}

@JsonTypeName({value: 'cat'})
class Cat extends Animal {

}

Const JsonTypeName

JsonTypeName: JsonTypeNameDecorator = makeJacksonDecorator((o: JsonTypeNameOptions): JsonTypeNameOptions => ({enabled: true, ...o}),(options: JsonTypeNameOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {options._ctor = target;if (!options.value) {options.value = (target as ObjectConstructor).name;}defineMetadata('JsonTypeName', options, target);defineMetadata('JsonTypeName', options, target, null, {suffix: options.value});defineMetadata('JsonTypeName', options, target, null, {suffix: (target as ObjectConstructor).name});return target;}})

Decorator used for binding logical name that the decorated class has. Used with JsonTypeInfo.

Usage example

@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;
}

@JsonTypeName({value: 'dog'}) class Dog extends Animal {

}

@JsonTypeName({value: 'cat'}) class Cat extends Animal {

}

Const JsonUnwrapped

JsonUnwrapped: JsonUnwrappedDecorator = makeJacksonDecorator((o: JsonUnwrappedOptions = {}): JsonUnwrappedOptions => ({enabled: true,prefix: '',suffix: '',...o}),(options: JsonUnwrappedOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null) {defineMetadata('JsonUnwrapped', options, target.constructor, propertyKey);defineMetadata('JsonUnwrapped', options, target.constructor, null, {suffix: propertyKey.toString()});}})

Decorator used to indicate that a property should be serialized "unwrapped"; that is, if it would be serialized as JSON Object, its properties are instead included as properties of its containing Object.

It cannot be applied on Iterables and in conjunction of JsonTypeInfo as it requires use of type information.

Usage example

class User {
  @JsonProperty() @JsonClassType({type: () => [Number]})
  id: number;
  @JsonProperty()
  @JsonUnwrapped()
  @JsonClassType({type: () => [Name]})
  name: Name;
}

class Name {
  @JsonProperty() @JsonClassType({type: () => [String]})
  first: string;
  @JsonProperty() @JsonClassType({type: () => [String]})
  last: string;
}

Const JsonValue

JsonValue: JsonValueDecorator = makeJacksonDecorator((o: JsonValueOptions): JsonValueOptions => ({enabled: true, ...o}),(options: JsonValueOptions, target, propertyKey, descriptorOrParamIndex) => {if (propertyKey != null) {if (hasMetadata('JsonValue', target.constructor, null, {withContextGroups: options.contextGroups})) {throw new JacksonError(`Multiple @JsonValue() decorators for ${target.constructor}.'`);}defineMetadata('JsonValue', options, target.constructor);}})

Decorator that 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.

At most one accessor of a Class can be decorated with this decorator; if more than one is found, an exception may be thrown.

Usage example

class Company {
  @JsonProperty() @JsonClassType({type: () => [String]})
  name: string;
  @JsonProperty()
  @JsonClassType({type: () => [Array, [Employee]]})
  employees: Employee[] = [];
}

class Employee {
  @JsonProperty() @JsonClassType({type: () => [String]})
  name: string;
  @JsonProperty() @JsonClassType({type: () => [Number]})
  age: number;

  @JsonValue()
  toEmployeeInfo(): string {
    return this.name + ' - ' + this.age;
  }
}

Const JsonView

JsonView: JsonViewDecorator = makeJacksonDecorator((o: JsonViewOptions): JsonViewOptions => ({enabled: true, ...o}),(options: JsonViewOptions, target, propertyKey, descriptorOrParamIndex) => {if (descriptorOrParamIndex == null && propertyKey == null) {defineMetadata('JsonView', options, target);return target;}if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') {defineMetadata('JsonViewParam',options, (target.constructor.toString().endsWith('{ [native code] }')) ? target : target.constructor,(propertyKey) ? propertyKey : 'constructor', {suffix: descriptorOrParamIndex.toString()});}if (propertyKey != null) {defineMetadata('JsonView', options, target.constructor, propertyKey);}})

Decorator 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, 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.

Usage example

class Views {
  static public = class Public {};
  static internal = class Internal {};
}

class User {
  @JsonProperty() @JsonClassType({type: () => [Number]})
  id: number;
  @JsonProperty() @JsonClassType({type: () => [String]})
  email: string;
  @JsonProperty() @JsonClassType({type: () => [String]})
  @JsonView({value: () => [Views.internal]})
  password: string;
  @JsonProperty() @JsonClassType({type: () => [String]})
  firstname: string;
  @JsonProperty() @JsonClassType({type: () => [String]})
  lastname: string;
  @JsonProperty() @JsonClassType({type: () => [String]})
  @JsonView({value: () => [Views.internal]})
  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]
});

Const defaultCreatorName

defaultCreatorName: "defaultCreatorName" = "defaultCreatorName"

Default creator name used by JsonCreator.

Generated using TypeDoc