TypedJSON
TypedJSON copied to clipboard
Examples for using with constructor parameters / DI
Hi,
Are there any examples available, on how to use typedjson with constructor parameters / DI? I thought about using a custom deserializer function for that purpose, but couldn't find any docs or examples.
Thanks
regards Benny
Hi, @Benny739
A parameterless constructor by default is required, as TypedJSON will automatically instantiate the deserialized objects. This is satisfied by at least one such call signature, such as:
class DITarget {
constructor(dependency?: DISource) {
// ...
}
}
Note the optional dependency parameter. In cases where it's not possible to have a parameterless constructor signature, an initializer setting must be supplied to JsonObject, such as:
@JsonObject({
initializer: (sourceObject) => Object.assign(new DITarget(new DISource()), sourceObject)
})
class DITarget {
constructor(dependency: DISource) {
// ...
}
}
However, as per the current release, this functionality has been pretty much just duct-taped to TypedJSON (hence the lack of documentation), and it has its issues:
sourceObjectis the rawObjectinstance from which the object is being deserialized; the implication here is that you'll need to manually deserialize child objects, otherwise they'll end up as simpleObjectinstances (i.e. without any expected methods); this is not a problem with primitive (number/string/boolean) properties, of course- The
initializeroption is simply not feasible to use, and in many cases requires various workarounds to be applied (such as when a single dependency object is to be injected into multiple deserialized objects)
I perfectly understand this feature has (would have) its valid use-cases, and the new release will contain a more powerful and flexible approach. It's around the clock, I'm currently testing polymorphic object-tree serialization with the new (read: completely revamped) code.