• Guest
HabraHabr
  • Main
  • Users

  • Development
    • Programming
    • Information Security
    • Website development
    • JavaScript
    • Game development
    • Open source
    • Developed for Android
    • Machine learning
    • Abnormal programming
    • Java
    • Python
    • Development of mobile applications
    • Analysis and design of systems
    • .NET
    • Mathematics
    • Algorithms
    • C#
    • System Programming
    • C++
    • C
    • Go
    • PHP
    • Reverse engineering
    • Assembler
    • Development under Linux
    • Big Data
    • Rust
    • Cryptography
    • Entertaining problems
    • Testing of IT systems
    • Testing Web Services
    • HTML
    • Programming microcontrollers
    • API
    • High performance
    • Developed for iOS
    • CSS
    • Industrial Programming
    • Development under Windows
    • Image processing
    • Compilers
    • FPGA
    • Professional literature
    • OpenStreetMap
    • Google Chrome
    • Data Mining
    • PostgreSQL
    • Development of robotics
    • Visualization of data
    • Angular
    • ReactJS
    • Search technologies
    • Debugging
    • Test mobile applications
    • Browsers
    • Designing and refactoring
    • IT Standards
    • Solidity
    • Node.JS
    • Git
    • LaTeX
    • SQL
    • Haskell
    • Unreal Engine
    • Unity3D
    • Development for the Internet of things
    • Functional Programming
    • Amazon Web Services
    • Google Cloud Platform
    • Development under AR and VR
    • Assembly systems
    • Version control systems
    • Kotlin
    • R
    • CAD/CAM
    • Customer Optimization
    • Development of communication systems
    • Microsoft Azure
    • Perfect code
    • Atlassian
    • Visual Studio
    • NoSQL
    • Yii
    • Mono и Moonlight
    • Parallel Programming
    • Asterisk
    • Yandex API
    • WordPress
    • Sports programming
    • Lua
    • Microsoft SQL Server
    • Payment systems
    • TypeScript
    • Scala
    • Google API
    • Development of data transmission systems
    • XML
    • Regular expressions
    • Development under Tizen
    • Swift
    • MySQL
    • Geoinformation services
    • Global Positioning Systems
    • Qt
    • Dart
    • Django
    • Development for Office 365
    • Erlang/OTP
    • GPGPU
    • Eclipse
    • Maps API
    • Testing games
    • Browser Extensions
    • 1C-Bitrix
    • Development under e-commerce
    • Xamarin
    • Xcode
    • Development under Windows Phone
    • Semantics
    • CMS
    • VueJS
    • GitHub
    • Open data
    • Sphinx
    • Ruby on Rails
    • Ruby
    • Symfony
    • Drupal
    • Messaging Systems
    • CTF
    • SaaS / S+S
    • SharePoint
    • jQuery
    • Puppet
    • Firefox
    • Elm
    • MODX
    • Billing systems
    • Graphical shells
    • Kodobred
    • MongoDB
    • SCADA
    • Hadoop
    • Gradle
    • Clojure
    • F#
    • CoffeeScript
    • Matlab
    • Phalcon
    • Development under Sailfish OS
    • Magento
    • Elixir/Phoenix
    • Microsoft Edge
    • Layout of letters
    • Development for OS X
    • Forth
    • Smalltalk
    • Julia
    • Laravel
    • WebGL
    • Meteor.JS
    • Firebird/Interbase
    • SQLite
    • D
    • Mesh-networks
    • I2P
    • Derby.js
    • Emacs
    • Development under Bada
    • Mercurial
    • UML Design
    • Objective C
    • Fortran
    • Cocoa
    • Cobol
    • Apache Flex
    • Action Script
    • Joomla
    • IIS
    • Twitter API
    • Vkontakte API
    • Facebook API
    • Microsoft Access
    • PDF
    • Prolog
    • GTK+
    • LabVIEW
    • Brainfuck
    • Cubrid
    • Canvas
    • Doctrine ORM
    • Google App Engine
    • Twisted
    • XSLT
    • TDD
    • Small Basic
    • Kohana
    • Development for Java ME
    • LiveStreet
    • MooTools
    • Adobe Flash
    • GreaseMonkey
    • INFOLUST
    • Groovy & Grails
    • Lisp
    • Delphi
    • Zend Framework
    • ExtJS / Sencha Library
    • Internet Explorer
    • CodeIgniter
    • Silverlight
    • Google Web Toolkit
    • CakePHP
    • Safari
    • Opera
    • Microformats
    • Ajax
    • VIM
  • Administration
    • System administration
    • IT Infrastructure
    • *nix
    • Network technologies
    • DevOps
    • Server Administration
    • Cloud computing
    • Configuring Linux
    • Wireless technologies
    • Virtualization
    • Hosting
    • Data storage
    • Decentralized networks
    • Database Administration
    • Data Warehousing
    • Communication standards
    • PowerShell
    • Backup
    • Cisco
    • Nginx
    • Antivirus protection
    • DNS
    • Server Optimization
    • Data recovery
    • Apache
    • Spam and antispam
    • Data Compression
    • SAN
    • IPv6
    • Fidonet
    • IPTV
    • Shells
    • Administering domain names
  • Design
    • Interfaces
    • Web design
    • Working with sound
    • Usability
    • Graphic design
    • Design Games
    • Mobile App Design
    • Working with 3D-graphics
    • Typography
    • Working with video
    • Work with vector graphics
    • Accessibility
    • Prototyping
    • CGI (graphics)
    • Computer Animation
    • Working with icons
  • Control
    • Careers in the IT industry
    • Project management
    • Development Management
    • Personnel Management
    • Product Management
    • Start-up development
    • Managing the community
    • Service Desk
    • GTD
    • IT Terminology
    • Agile
    • Business Models
    • Legislation and IT-business
    • Sales management
    • CRM-systems
    • Product localization
    • ECM / EDS
    • Freelance
    • Venture investments
    • ERP-systems
    • Help Desk Software
    • Media management
    • Patenting
    • E-commerce management
    • Creative Commons
  • Marketing
    • Conferences
    • Promotion of games
    • Internet Marketing
    • Search Engine Optimization
    • Web Analytics
    • Monetize Web services
    • Content marketing
    • Monetization of IT systems
    • Monetize mobile apps
    • Mobile App Analytics
    • Growth Hacking
    • Branding
    • Monetize Games
    • Display ads
    • Contextual advertising
    • Increase Conversion Rate
  • Sundry
    • Reading room
    • Educational process in IT
    • Research and forecasts in IT
    • Finance in IT
    • Hakatonas
    • IT emigration
    • Education abroad
    • Lumber room
    • I'm on my way

TypeScript: Deserializing JSON into classes with property type validation

 3r3179. 3r3-31. Hi, Habr! I want to share with you my library for deserializing JSON objects into classes, which also automatically validates input data by type.
 3r3179.
 3r3179. Not so long ago in jаvascript there was such a wonderful thing as classes, which greatly simplified the process of writing code. But unfortunately, there is no functionality for deserializing JSON into these same classes, i.e. You can serialize a class into a string, but you can do it yourself. And to correct this deficiency, the library was written. ts-serializable which I want to share with you.
 3r3179.
3r311.
 3r3179. The essence of the problem is shown by the following code:
 3r3179.
 3r3179.
export class User {3r3179. public firstName: string = "Ivan"; 3r3179. public lastName: string = "Petrov"; 3r3179. public birthDate: Date = new Date (); 3r3179. 3r3179. public getFullName (): string {
return[this.firstName, this.lastName].join (""); 3r3179.}
3r3179. public getAge (): number {
return new Date (). getFullYear () - this.birthDate.getFullYear (); 3r3179.}
}
3r3179. const ivan = new User (); 3r3179. ivan.getFullName (); //returns the full name
ivan.getAge (); //returns age
ivan instanceof User; //is the user instance of
3r3179. const text = JSON.stringify (ivan); //serialize the class to text
const newIvan = JSON.parse (text); //we deserialize back
3r3179. newIvan.getFullName (); //ErrorType: the getFullName method is missing
newIvan.getAge (); //ErrorType: the getAge method is missing
newIvan instanceof User; //is not a user instance
3r3167. 3r3168.
 3r3179. What is the reason for the mistakes of the new Ivan? The fact is that the JSON.parse method deserializes not into the User class, but into the Object class, which simply does not have the getFullName and getAge methods.
 3r3179.
 3r3179. How does my library help solve this problem and deserialize into User, not Object? It is enough just to slightly modify the code:
 3r3179.
 3r3179.
import {jsonProperty, Serializable} from "ts-serializable"; 3r3179. 3r3179. export class User extends Serializable {
@jsonProperty (String)
public firstName: string = "Ivan"; 3r3179. @jsonProperty (String)
public lastName: string = "Petrov"; 3r3179. @jsonProperty (Date)
public birthDate: Date = new Date (); 3r3179. 3r3179. public getFullName (): string {
return[this.firstName, this.lastName].join (""); 3r3179.}
3r3179. public getAge (): number {
return new Date (). getFullYear () - this.birthDate.getFullYear (); 3r3179.}
}
3r3179. const ivan = new User (); 3r3179. ivan.getFullName (); //returns the full name
ivan.getAge (); //returns age
ivan instanceof User; //is the user instance of
3r3179. const text = JSON.stringify (ivan); //serialize the class to text
const newIvan = new User (). fromJson (JSON.parse (text)); //we deserialize back to User
3r3179. newIvan.getFullName (); //returns the full name
newIvan.getAge (); //returns age
newIvan instanceof User; //is the user instance of
3r3167. 3r3168.
 3r3179. Everything is very simple. We inherit our class from the Serializable class, which has two fromJson methods for deserialization and toJSON for serialization, and the properties are hung by the @jsonProperty decorator with an indication of the data types that can be accepted from JSON. Empty data will be ignored, a warning will be issued to the console, and the default value will remain in the property.
 3r3179.
 3r3179. That's all that's all. Now on the front, you can deserialize and serialize as easily as it does in C #, Java, and other languages. The basis for the behavior of Newtonsoft Json.NET.
 3r3179.
 3r3179. 3r3147. FAQ
 3r3179. Why inherit from Serializable?
 3r3179.
 3r3179. In order to add two methods fromJson and toJSON to the model. You can do the same thing through a decorator or monkey patching. But inheritance is a better method for typescript.
 3r3179.
 3r3179. How does data validation
 3r3179.
 3r3179. In the decorator, you must assign the constructor of the data types that are allowed to receive from JSON. Objects Boolean, String, Number will be given, respectively, boolean, string, number. If you need to accept an array, then the type is framed by array brackets, for example @jsonProperty ([String]). If the constructor is inherited from the Serializable class, it will also be deserialized into the class, if not, the object will be returned.
 3r3179.
 3r3179. How to catch validation errors?
 3r3179.
 3r3179. By default, the library simply writes warnings to the validation error console. To override this behavior, for example, to throw exceptions or logging to the backend, you need to override the model's onWrongType method.
 3r3179.
 3r3179. 3r3147. Bonus 1. Deep copy. 3r3148.
 3r3179.
const user1 = new Uesr (); 3r3179. const user2 = new User (). fromJson (user1); //create a deep copy of
3r3167. 3r3168.
 3r3179. 3r3147. Bonus 2. Lazy ViewModels. 3r3148.
 3r3179. If you need to create a model with additional data, for example, for a view, but which does not accept the backend, you can simply expand the model with new properties and mark these properties with the @jsonIgnore decorator. And then these properties will not be serialized.
 3r3179.
 3r3179.
import {jsonProperty, Serializable} from "ts-serializable"; 3r3179. 3r3179. export class User extends Serializable {
@jsonProperty (String)
public firstName: string = "Ivan"; 3r3179. @jsonIgnore ()
public isExpanded: boolean = false; 3r3179.}
3r3179. JSON.stringify (new User ()); //returns {"firstName": "Ivan"}
3r3167. 3r3168. 3r33175. 3r3179. 3r3179. 3r3172. ! function (e) {function t (t, n) {if (! (n in e)) {for (var r, a = e.document, i = a.scripts, o = i.length; o-- ;) if (-1! == i[o].src.indexOf (t)) {r = i[o]; break} if (! r) {r = a.createElement ("script"), r.type = "text /jаvascript", r.async =! ? r.defer =! ? r.src = t, r.charset = "UTF-8"; var d = function () {var e = a.getElementsByTagName ("script")[0]; e.parentNode.insertBefore (r, e)}; "[object Opera]" == e.opera? a.addEventListener? a.addEventListener ("DOMContentLoaded", d,! 1): e.attachEvent ("onload", d ): d ()}}} t ("//mediator.mail.ru/script/2820404/"""_mediator") () (); 3r3173. 3r3179. 3r33175. 3r3179. 3r3179. 3r3179. 3r3179.

It may be interesting

  • Comments
  • About article
  • Similar news
This publication has no comments.

weber

Author

6-11-2018, 05:38

Publication Date

Development / TypeScript

Category
  • Comments: 0
  • Views: 394
We had old school games and a few
Raise the awareness of citizens
Amplifiers of low frequency classes: A,
RADIOTEHNKIKA S-30 speakers from old to
[Микро-навигация (микро-подталкивание)
"Back to the roots": why the IT giant
Write a comment
Name:*
E-Mail:


Comments
this is really nice to read..informative post is very good to read..thanks a lot! How is the cost of house cleaning calculated?
Yesterday, 17:14

Legend SEO

It’s very informative and you are obviously very knowledgeable in this area. You have opened my eyes to varying views on this topic with interesting and solid content.

entegrasyon programları
Yesterday, 17:09

taxiseo2

I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.

entegrasyon programları
Yesterday, 17:02

taxiseo2

I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work...먹튀

Yesterday, 16:50

raymond weber

Lose Weight Market provides the best fitness tips, workout guides, keto recipes and diet plans, yoga workout routine and plans, healthy recipes, and more! Check Out: Lose Weight Market


Corvus Health provides medical training services as well as recruiting high quality health workers for you or placing our own best team in your facility. Check Out: Health Workforce Recruitment




I.T HATCH offers a wide range of IT services including remote access setup, small business servers, data storage solutions, IT strategy services, and more. Check Out: IT strategy services
Yesterday, 22:33

noorseo

Adv
Website for web developers. New scripts, best ideas, programming tips. How to write a script for you here, we have a lot of information about various programming languages. You are a webmaster or a beginner programmer, it does not matter, useful articles will help to make your favorite business faster.

Login

Registration Forgot password