Type-Aware JSON Parser & Serializer (ta-json)
This package is a fork of a fork
-
This package was published as "ta-json-xx" in NPM. Its source code is forked from https://github.com/danielweck/ta-json.git. Compare: https://github.com/danielweck/ta-json/compare/master...nicky1038:master
-
That repo, in its turn, was published as "ta-json-x" and is forked from https://github.com/edcarroll/ta-json.git Compare: https://github.com/edcarroll/ta-json/compare/master...danielweck:master
Description
Strongly typed JSON parser & serializer for TypeScript / ES7 via decorators.
Supports parameterized class constructors, nesting classes, inheritance, Array
s and Set
s, custom property converters and more.
Installation
$ npm install --save ta-json
Quickstart
Import the necessary decorators and the JSON object from the library, and set up your class.
;
Parse and stringify with the provided JSON class. Note that you can use this class to work with untyped objects as usual.
;JSON.stringifyperson; // {"firstName":"Edward","lastName":"Carroll"} ;person instanceof Person; // trueperson.fullName; // Edward Carroll
For more advanced usage please read the docs below for each of the available decorators.
JSON
object
Overriding the This library doesn't make any changes to the global scope, it merely exports its main class with the same name, allowing it to be a drop in replacement for JSON
(without any decorators, the library falls back to default functionality).
If you'd prefer to import the library with a different name, you can also import TaJson
, which will give you the same class.
;
Decorators
@JsonObject()
Registers the class with the serializer. Classes don't need to have parameterless constructors to be serialized and parsed - however this means that the internal state of a class must be fully represented by its serialized fields.
If you would like to run functions before and after deserialization, please see @BeforeDeserialized() and @OnDeserialized()
Usage
;
@JsonProperty(serializedName?:string)
Properties are mapped on an opt-in basis. Only properties that are decorated are serialized. The name for the property in the serialized document can optionally be specified using this decorator.
Usage
;
@JsonType(type:Function)
Specifies the type to be used when serializing a property. Useful when you want to serialize the field using a different type than the type of the property itself, for example an entity reference.
Usage
;
@JsonElementType(type:Function)
Specifies the type to be used when serializing elements of an Array
or Set
. This is a required decorator when working with these types due to how metadata reflection works.
Usage
;
@JsonDiscrimatorProperty(property:string) & @JsonDiscriminatorValue(value:any)
These decorators are used when you want to deserialize documents while respecting the class inheritance hierarchy. The discriminator property is used to determine the type of the document, and the descriminator value is set on each subclass (or deeper subclasses) so the document can be matched to the appropriate class.
Multi-level inheritance is fully supported, by the @JsonDiscriminatorValue and the @JsonDiscriminatorProperty decorators being applied to the same class.
Usage
; ; JSON.stringifyanimals; // [{"type":0},{"type":1}]JSON.parse'[{"type":0},{"type":1}]', Animal; // [ Cat { type: 0 }, Dog { type: 1 } ]
@BeforeDeserialized()
Specifies the method to run before a document has been deserialized into a class, but after the class has been instantiated. This is useful for setting default values that may be overwritten by the deserialization.
Usage
;
@OnDeserialized()
Specifies the method to run once a document has been deserialized into a class. This is useful for example when recalculating private members that aren't serialized into JSON.
Usage
;
@JsonConstructor()
Specifies the method to be optionally run before a document has been deserialized. The specified method is only run when runConstructor
is set to true
in the parse options.
Usage
; JSON.parse'{}', Demo, ; // Demo { example: 'default' }JSON.parse'{"example":"different"}', Demo, // Demo { example: 'different' }JSON.parse'{}', Demo; // Demo {}
@JsonConverter(converter:IPropertyConverter | ParameterlessConstructor)
Property converters can be used to define how a type is serialized / deserialized. They must implement the IPropertyConverter
interface, and output a JsonValue
.
There are two built in converters, DateConverter
and BufferConverter
. They are applied automatically when serializing Date
and Buffer
objects.
Example
This example uses the built in BufferConverter
, to output Buffer values as base64 encoded strings. Note that when parsing documents, the deserializer will convert the value back into a Buffer.
; ;JSON.stringifydemo; // {"bufferValue":"aGVsbG8sIHdvcmxkIQ=="};parsed.bufferValue instanceof Buffer; // trueparsed.bufferValue.toString; // hello, world!
Usage
Below we define a converter that reverses any string value it is given.
; ;d.example = "hello";JSON.stringifyd; // {"example":"olleh"}
Note that you can also provide an instance of a property converter, for example if you want to customize the output. (This is how the BufferConverter
chooses a string encoding).
@JsonReadonly()
The use of this decorator stops the property value being read from the document by the deserializer.
Usage
; JSON.parse'{"name":"Edward"}', Person.name; // undefined
@JsonWriteonly()
The use of this decorator stops the property value being written to the document by the serializer. Useful for password fields for example.
Usage
; ;u.password = "p4ssw0rd"; JSON.stringifyu; // {}JSON.parse'{"password":"p4ssw0rd"}', User.password; // p4ssw0rd
API
TaJson
)
JSON (can also be imported with #stringify(value:any):string
Serializes an object or array into a JSON string. If type definitions aren't found for a given object it falls back to global.JSON.stringify(value)
.
#parse(json:string, type?:Function, options?:IParseOptions):T
Parses a JSON string into an instance of a class. the type
parameter specifies which class to instantiate; however this is an optional parameter and as with #stringify
it will fall back to global.JSON.parse(json)
.
IParseOptions
- runConstructor:boolean - specifies whether the method decorated with @JsonConstructor() is run upon class initialisation. Default
false
#serialize(value:any):any
Serializes an object or array into a JsonValue
. This is an intermediary step; i.e. global.JSON.stringify
can be called on the returned object to get a JSON string. This function is useful when returning from inside an express (o.e) middleware.
#deserialize(object:any, type?:Function, options?:IParseOptions):T
Similarly to the above, this function can be run on objects produced by global.JSON.parse
, returning the same output as #parse
. This function is useful in combination with body parsing modules, where the raw JSON has already been parsed into an object.