This is an aproach to get GSON (Google JSON seralization/deserialization) functionality into TypeScript.
This version uses awesome-metadata to emit additional metadata for all classes.
If you don't want to use awesome-metadata
, you can check the branch decorator to use decorators instead.
Awesome metadata does not yet emit information for interfaces, so there is no serialization/deserialization for classes which uses interfaces.
First, you have to emit metadata of classes using atm
in your TypeScript project folder command:
node_modules/.bin/atm > metadata.ts
And then you have to import metadata anywhere in you code:
import "./metadata"
After doing this, you can use anywhere the library:
import * as TSON from "typescript-son";
const el = new AnyClass(...);
// Serialize
const ser = TSON.toJson(el);
// Deserialize
const el2 = TSON.fromJson(AnyClass, ser);
If you try to deserialize a class with a wrong JSON object, it will throw an IncompatibleSchemaError
.