After many hours of development, I finally released the first version of the jackson-js
library. As the name implies, jackson-js
decorators are heavily inspired by the Java annotations of the famous Java FasterXML/jackson library.
You can install it using npm install —-save jackson-js
and it can be used on both client (browser) and server (Node.js) side.
Why this library? What’s the difference between using this library instead of JSON.parse
and JSON.stringify
?
For simple cases, you don't need this library of course, you can just use JSON.parse
and JSON.stringify
to serialize/deserialize JSON.
With jackson-js
, you can easily manipulate your JavaScript objects/values serialization/deserialization using decorators such as @JsonProperty()
, @JsonFormat()
, @JsonIgnore()
, and more. However, this library uses JSON.parse
and JSON.stringify
under the hood.
Furthermore:
- it not only deserialize JSON text into a JavaScript object, it also converts it into an instance of the class specified in the
context
option (similar packages are: class-transformer and TypedJSON); instead, withJSON.parse
you will get just a simple plain (literal) JavaScript object (justObject
type); - it supports more advanced Object concepts such as polymorphism and Object identity;
- it supports cyclic object serialization/deserialization;
- it supports serialization/deserialization of other native JavaScript types:
Map
,Set
,BigInt
, Typed Arrays (such asInt8Array
);
This library can be useful in more complex cases, for example when you want to:
- manipulate JSON in depth;
- restore a JavaScript type (a similar package is class-transformer);
- preserve type information (using polymorphic type handling decorators:
@JsonTypeInfo
,@JsonSubTypes
, and@JsonTypeName
. A similar package is TypedJSON); - hide some properties for certain HTTP endpoints or some other external service;
- have different JSON response for some external application or manage different JSON data coming from other application (for example you need to communicate with a Spring Boot application that uses different JSON Schema for the same model or with other applications made with Python, PHP, etc...);
- manage cyclic references;
- manage other JavaScript native types such as Maps and Sets;
- etc.
Most of the use cases of the Java FasterXML/jackson annotations are similar or equal.
In this article, I will present a basic example for each decorator.
ObjectMapper, JsonParser and JsonStringifier classes
The main classes that jackson-js
offers to serialize and deserialize JavaScript objects are: ObjectMapper
, JsonStringifier
and JsonParser
.
ObjectMapper
ObjectMapper
provides functionality for both reading and writing JSON and applies jackson-js
decorators. It will use instances of JsonParser
and JsonStringifier
for implementing actual reading/writing of JSON. It has two methods:
-
stringify(obj: T, context?: JsonStringifierContext): string
: a method for serializing a JavaScript object or a value to a JSON string with decorators applied; -
parse(text: string, context?: JsonParserContext): T
: a method for deserializing a JSON string into a JavaScript object/value (of typeT
, based on the context given) with decorators applied.
JsonParser
JsonParser
provides functionality for writing JSON and applies jackson-js
decorators. The main methods are:
-
parse(text: string, context?: JsonParserContext): T
: a method for deserializing a JSON string into a JavaScript object/value (of typeT
, based on the context given) with decorators applied; -
transform(value: any, context?: JsonParserContext): any
: a method for applyingjackson-js
decorators to a JavaScript object/value parsed. It returns a JavaScript object/value with decorators applied.
JsonStringifier
JsonStringifier
provides functionality for reading JSON and applies jackson-js
decorators. The main methods are:
-
stringify(obj: T, context?: JsonStringifierContext): string
: a method for serializing a JavaScript object or a value to a JSON string with decorators applied; -
transform(value: any, context?: JsonStringifierContext): any
: a method for applyingjackson-js
decorators to a JavaScript object/value. It returns a JavaScript object/value with decorators applied and ready to be JSON serialized.
Decorators
Before we go on, I need to say that the most important decorators are:
-
@JsonProperty()
: each class property (or its getter/setter) must be decorated with this decorator, otherwise deserialization and serialization will not work properly! That's because, for example, given a JavaScript class, there isn't any way or API (such as Reflection API for Java) to get for sure all the class properties; also because, sometimes, compilers such as TypeScript and Babel, can strip class properties after compilation from the class properties declaration; -
@JsonClassType()
: this decorator, instead, is used to define the type of a class property or method parameter. This information is used during serialization and, more important, during deserialization to know about the type of a property/parameter. This is necessary because JavaScript isn't a strongly-typed programming language, so, for example, during deserialization, without the usage of this decorator, there isn't any way to know the specific type of a class property, such as aDate
or a custom Class type.
Later, they will be explained in more detail.
@JsonAlias
The @JsonAlias
decorator defines one or more alternative names for a property during deserialization.
API: JsonAlias - decorator options JsonAliasOptions.
@JsonAnyGetter
The @JsonAnyGetter
decorator allows the flexibility of using a Map or an Object Literal field as standard properties.
API: JsonAnyGetter - decorator options JsonAnyGetterOptions.
@JsonAnySetter
@JsonAnySetter
allows us to define a logical "any setter" mutator using a non-static two-argument method to be used as a "fallback" handler for all otherwise unrecognized properties found from JSON content.
API: JsonAnySetter - decorator options JsonAnySetterOptions.
@JsonAppend
@JsonAppend
can be used to add "virtual" properties to be written after regular properties.
API: JsonAppend - decorator options: JsonAppendOptions.
@JsonManagedReference and @JsonBackReference
The @JsonManagedReference
and @JsonBackReference
decorators can handle parent/child relationships and work around loops.
API: JsonManagedReference - decorator options JsonManagedReferenceOptions, JsonBackReference - decorator options JsonBackReferenceOptions.
@JsonClassType
As said before, the @JsonClassType
is used to define the type of a class property or method parameter. A type is defined as an Array of JavaScript classes, such as [Number]
for properties of type number or [Array, [Number]]
for properties of type Array<number>
or [Map, [String, Object]]
for properties of type Map<string, any>
.
Why an Array of JavaScript classes? Because in this way you can map complex types such as Map<string, any>
using [Map, [String, Object]]
or Array<Set<any>>
using [Array, [Set, [Object]]]
.
API: JsonClassType - decorator options JsonClassTypeOptions.
@JsonCreator
We can use the @JsonCreator
decorator to define constructors and factory methods as one to use for instantiating new instances of the associated class.
It’s very helpful when we need to deserialize some JSON that doesn’t exactly match the target entity we need to get, also with the help of the @JsonProperty
decorator.
API: JsonCreator - decorator options JsonCreatorOptions.
@JsonSerialize and @JsonDeserialize
@JsonSerialize
and @JsonDeserialize
are used to indicates the use of a custom serializer/deserializer.
API: JsonSerialize - decorator options JsonSerializeOptions, JsonDeserialize - decorator options JsonDeserializeOptions.
@JsonFilter
@JsonFilter
can be used to indicate which logical filter is to be used for filtering out properties of type (class) decorated.
API: JsonFilter - decorator options JsonFilterOptions.
@JsonFormat
@JsonFormat
is a general-purpose decorator used for configuring details of how values of properties are to be serialized.
API: JsonFormat - decorator options JsonFormatOptions.
@JsonGetter and @JsonSetter
@JsonGetter
and @JsonSetter
are alternatives to more general @JsonProperty
decorator to mark a method as a getter/setter method for a logical property.
API: JsonGetter - decorator options: JsonGetterOptions, JsonSetter - decorator options JsonSetterOptions.
@JsonIdentityInfo
@JsonIdentityInfo
indicates that Object Identity should be used when serializing/deserializing values - for instance, to deal with infinite recursion type of problems.
API: JsonIdentityInfo - decorator options JsonIdentityInfoOptions.
@JsonIdentityReference
@JsonIdentityReference
can be used for customizing details of a reference to Objects for which "Object Identity" is enabled (see @JsonIdentityInfo
). The main use case is that of enforcing the use of Object Id even for the first time an Object is referenced, instead of the first instance being serialized as full Class.
API: JsonIdentityReference - decorator options JsonIdentityReferenceOptions.
@JsonIgnore, @JsonIgnoreProperties, and @JsonIgnoreType
@JsonIgnore
is used to mark a property to be ignored at the field level during serialization and deserialization.
API: JsonIgnore - decorator options JsonIgnoreOptions.
@JsonIgnoreProperties
can be used as a class-level decorator that marks a property or a list of properties that will be ignored during serialization and deserialization.
API: JsonIgnoreProperties - decorator options JsonIgnorePropertiesOptions.
@JsonIgnoreType
indicates that all properties of decorated type are to be ignored during serialization and deserialization.
API: JsonIgnoreType - decorator options JsonIgnoreTypeOptions.
@JsonInclude
@JsonInclude
can be used to exclude properties with empty/null/default values.
API: JsonInclude - decorator options JsonIncludeOptions.
@JsonInject
@JsonInject
decorator is used to indicate that value of decorated property will be injected during deserialization.
API: JsonInject - decorator options JsonInjectOptions.
@JsonNaming
@JsonNaming
decorator is used to choose the naming strategies (SNAKE_CASE
, UPPER_CAMEL_CASE
, LOWER_CAMEL_CASE
, LOWER_CASE
, KEBAB_CASE
, and LOWER_DOT_CASE
) for properties in serialization, overriding the default.
API: JsonNaming - decorator options JsonNamingOptions.
@JsonProperty
@JsonProperty
can be used to define a non-static method as a "setter" or "getter" for a logical property or non-static object field to be used (serialized, deserialized) as a logical property.
API: JsonProperty - decorator options JsonPropertyOptions.
@JsonPropertyOrder
@JsonPropertyOrder
can be used to specify the order of properties on serialization.
API: JsonPropertyOrder - decorator options JsonPropertyOrderOptions.
@JsonRawValue
@JsonRawValue
decorator indicates that the decorated method or field should be serialized by including literal String value of the property as is, without quoting of characters. This can be useful for injecting values already serialized in JSON or passing javascript function definitions from server to a javascript client.
API: JsonRawValue - decorator options JsonRawValueOptions.
@JsonRootName
@JsonRootName
decorator is used - if wrapping is enabled - to specify the name of the root wrapper to be used.
API: JsonRootName - decorator options JsonRootNameOptions.
Polymorphic Type Handling Decorators: @JsonTypeInfo, @JsonSubTypes, and @JsonTypeName
-
@JsonTypeInfo
: indicates details of what type information to include in serialization; API: JsonTypeInfo - decorator options JsonTypeInfoOptions; -
@JsonSubTypes
: indicates sub-types of the annotated type; API: JsonSubTypes - decorator options JsonSubTypesOptions; -
@JsonTypeName
: defines a logical type name to use for annotated class; API: JsonTypeName - decorator options JsonTypeNameOptions.
@JsonTypeId
@JsonTypeId
decorator is used to indicate that the annotated property should be serialized as the type id when including polymorphic type information, rather than as a regular property. That polymorphic metadata is used during deserialization to recreate objects of the same subtypes as they were before serialization, rather than of the declared supertypes.
API: JsonTypeId - decorator options JsonTypeIdOptions.
@JsonTypeIdResolver
@JsonTypeIdResolver
decorator can be used to plug a custom type identifier handler to be used for converting between JavaScript types and type id included in JSON content.
API: JsonTypeIdResolver - decorator options JsonTypeIdResolverOptions.
@JsonUnwrapped
@JsonUnwrapped
defines values that should be unwrapped/flattened when serialized/deserialized.
API: JsonUnwrapped - decorator options JsonUnwrappedOptions.
@JsonValue
@JsonValue
decorator indicates that the value of decorated accessor (either field or "getter" method) is to be used as the single value to serialize for the instance, instead of the usual method of collecting properties of value.
API: JsonValue - decorator options JsonValueOptions.
@JsonView
@JsonView
decorator is used for indicating view(s) that the property that is defined by method or field decorated is part of. If multiple View class identifiers are included, the property will be part of all of them. It is also possible to use this decorator on classes to indicate the default view(s) for properties of the type, unless overridden by per-property decorator.
API: JsonView - decorator options JsonViewOptions.
Conclusion
In the next part ("Jackson-js: Examples for client (Angular) and server (Node.js) side (Part 2)"), I will give a simple example using jackson-js
with Angular 9 for the client side and two examples for the server side: one using Node.js + Express + SQLite3 (with Sequelize 5) and another one using Node.js + LoopBack 4.
Top comments (0)