Converting JSON to TypeScript with serialization and deserialization

I'm currently working on serializing TypeScript objects to JSON and vice versa. During this process, certain fields need to be transformed, such as converting `Date` objects to ISO 8601 strings and mapping enumerations to values required by the wire format. I am in the process of defining type definitions for both the TypeScript object and the JSON object in order to avoid using `any`. Are there any alternative patterns or best practices for achieving this?

Example

TypeScript Object:

{
  name: 'John Smith',
  title: 'Sr. Developer',
  dob: new Date('1990-05-01T09:00:00Z');
}

JSON Object:

{
  "name": "John Smith",
  "title": "Sr. Developer",
  "dob": "1990-05-01T09:00:00Z";
}

Below is the code snippet for serialization/deserialization along with the type definitions for the two formats:

interface Person {
    name: string;
    title: string;
    dob: Date;
}

interface JsonPerson {
    name: string;
    title: string;
    dob: string; // In ISO 8601 format
}

function serialize(person: Person): JsonPerson {
    const { dob, ...rest } = person;
    return {
        dob: dob.toISOString(),
        ...rest
    }
}

function deserialize(jsonPerson: JsonPerson): Person {
    const { dob, ...rest } = jsonPerson;
    return {
        dob: new Date(dob),
        ...rest
    }
}

Answer №1

The built-in Date.prototype.toJSON method already formats dates in the ISO string format, so there's no need to use dob.toISOString().

Your current approach is solid and aligns with my personal preference for explicit serialization/deserialization. I even created a video discussing this topic.

If you're interested in using a serialization library specifically for TypeScript that utilizes decorators, I recommend these two options:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for utilizing the randomColor library

Looking for guidance on incorporating the randomColor package from yarn to assign colors to various columns in a table within my project. Any examples or resources would be greatly appreciated! I am specifically working with React and Typescript. ...

Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined. The base class called model lo ...

Unable to retrieve template generated using the innerHTML directive in Angular 4

I am in need of accessing the elements of a dynamically created component's DOM through the innerHTML directive in Angular. Below is my main component: import {Component} from '@angular/core'; @Component({ selector: 'app-root', ...

Encoding an image within a dataTable using DataContractJsonSerializer

Currently, I am using DataContractJsonSerializer to serialize a DataTable and pass it as JSON in C#. The issue I am encountering is that all fields are being serialized as strings. While FirstName and LastName are correct, the Picture field is being serial ...

How can the Jackson structure of a class be obtained during serialization process?

Is it feasible for Jackson to generate a comprehensive list of the necessary fields for serializing and deserializing any given class? Jackson's process for serialization can be intricate. My objective is to dynamically determine the expected JSON st ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

Deciphering JSON in C# from the current thread

I am looking to perform JSON serialization on the same thread and then deserialize it using reflection. After successfully achieving serialization, here is the code snippet I used: Thread t = new Thread(new ThreadStart(empty)); string ser = JsonConvert.S ...

Is the "Illegal invocation" error popping up when using the POST method in AJAX?

Is there a way to retrieve JSON data using the POST method in Ajax? I attempted to use the code below but encountered an error: TypeError: Illegal invocation By following the link above, I was able to access JSON-formatted data. However, please note th ...

Converting CommonJS default exports into named exports / Unable to load ES module

I've encountered an issue while creating a Discord bot with discord.js using TypeScript. When attempting to run the resulting JavaScript code, I'm facing an error that states: import { Client, FriendlyError, SQLiteProvider } from 'discord.js ...

Typescript: Understanding the Optional Operator and Dealing with Null Ambiguity

Seeking guidance on writing clean code, particularly regarding a property with a backing field: get value(): string { return this._value; } set value(v: string) { this._value = v; } private _value?: string; It has come to my attention that this code is co ...

Encountering difficulty in fetching data from a service with ng-select

Currently, I am utilizing ng-select for a form that allows users to search for activities to add. The ng-select component triggers a function whenever something is typed into the field. This function then calls a service that fetches an array of activities ...

A guide on effectively indexing nested JSON objects in Solr

I am dealing with a json object structured like this: { "id" : "123", "name" : "aaa", "loc" : { "lat" : "", "lon" : "" }, } Recently, I integrated Solr and added a field as shown below: <field name="loc" type="string" indexed="true" s ...

Arranging objects in an array according to a predetermined criteria

Presented below is an array: [{"cod_nivel":"INC2","cod_modelo":"D"}, {"cod_nivel":"PRIM1","cod_modelo":"B"}, {"cod_nivel":"INC2","cod_modelo":"B"}, {"cod_nivel":"INC1","cod_modelo":"D"}, {"cod_nivel":"PRIM1" ...

Collaborate and apply coding principles across both Android and web platforms

Currently, I am developing a web version for my Android app. Within the app, there are numerous utility files such as a class that formats strings in a specific manner. I am wondering if there is a way to write this functionality once and use it on both ...

Using the spread operator to modify an array containing objects

I am facing a challenge with updating specific properties of an object within an array. I have an array of objects and I need to update only certain properties of a single object in that array. Here is the code snippet I tried: setRequiredFields(prevRequir ...

Tips for sending a JSON payload instead of XML in an iOS Objective-C request

In the past, I was sending an XML file as a body using the following code: [[NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><vs:ClientID version=\"0.4\" xmlns:vs=&b ...

Getting the keys of an object where the values are of a certain type using TypeScript

Currently, I'm tackling a standard filter function (excuse the technical jargon) The main goal is to create a matcher function that compares a specified property (propertyName: keyof T) of an object (item: T) with a search term (term: string). type P ...

Develop a JSON array of objects using a Dictionary in C#

I'm really stuck on this issue and I know there must be a simple solution out there that I just haven't discovered yet. My task is to generate an array of objects in JSON, a format that I am quite new to. The desired structure should resemble th ...

A method for performing precise division on numbers in JavaScript, allowing for a specific precision level (such as 28 decimal places)

I've searched extensively for a library that can handle division operations with more than 19 decimal places, but to no avail. Despite trying popular libraries like exact-math, decimal.js, and bignumber.js, I have not found a solution. How would you ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...