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;
}
}
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);
}
}
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).
@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
}
});
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;
}
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[] = [];
}
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:
@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);
}
}
Decorator used to indicates the use of a custom deserializer.
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;
}
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']
}
}
});
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;
};
}
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(' ');
}
}
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;
}
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.
@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;
}
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.
class Item {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [String]})
@JsonIgnore()
category: string;
}
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;
}
Decorator that indicates that all properties of decorated type are to be ignored during serialization and deserialization.
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;
}
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>;
}
Decorator used for indicating that value of decorated property will be "injected" through JsonParserContext.injectableValues value.
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
}
});
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;
}
Decorator that can be used to indicate a PropertyNamingStrategy to use for decorated class.
@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;
}
}
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];
}
}
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;
}
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);
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.
@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]});
Decorator used to indicates the use of a custom serializer.
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;
}
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(' ');
}
}
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 {
}
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';
}
}
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.
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 {
}
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 {
}
Decorator used for binding logical name that the decorated class has. Used with JsonTypeInfo.
@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 {
}
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;
}
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;
}
}
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]
});
Default creator name used by JsonCreator.
Generated using TypeDoc
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; } }