Typescript Serialization
Let jsonString = myMap. ToJson ( );Which can then be stashed away in local storage or the like. Deserialise a JSON string into a Map objectWe are going to do similar to implement the deserialisation part. It’s not quite the same though.
If we are serialising a Map object it makes sense to have the toJson method associated with an instance of a Map object. If we are deserialising into a new Map object we want the method associated with the class- like a static method in C#. The following illustrates the difference. Note – this time I am extending the MapConstructor object rather than the Map object. In TypeScript the MapConstructor object returns a reference to the Map function that created the object. So by extending the MapConstructor Typescript object I am associating the method with the object that created the instance of the map object.
I am associating the new method with the class and not the instance.Now associate our implementation directly with the Map object which itself implements MapConstructor. Let restoredMap: Map = Map. JsonToMap ( jsonString );That’s it – the Map object now has toJson and fromJson methods which handle our JSON conversion. The Set object suffers from the same limitations and can be extended in the same way.
Useful LinksMap and Set objects are part of the ES6 standard. TypeScript offers a strongly typed version of these collectionsMore detail about extending built in types in TypeScriptThe initial code to serialise and deserialise the Map object came from a stack overflow question i.e. I'm a software developer in Brisbane with over a range of sectors. I mostly specialise in JavaScript, C#,.NET, SQL Server and Dev Ops but in 15 years you naturally.I tinker round with code in my spare time the results of which sometimes end up on.
I am a wholly owned subsidiary of a 7 year old daughter who invented the concept of 'on demand'. Recent Posts.Top Posts.Categories. (3). (8). (4). (5).
(3). (3). (4). (4). (3). (6).
Typescript Class To Json
(4). (2). (5). (2)Archives.
Typescript Json Parsing
Typescript Xml Serialization
I started my IT career in programming on different embedded devices since 1992, such as credit card readers, smart card readers and Palm Pilot.Since 2000, I have mostly been developing business applications on Windows platforms while also developing some tools for myself and developers around the world, so we developers could focus more on delivering business values rather than repetitive tasks of handling technical details.Beside technical works, I enjoy reading literatures, playing balls, cooking and gardening.