Using JSON to create a JavaScript object that includes methods

I have a Typescript class with methods that get lost when transferring objects from the server to the browser via REST in JSON format. I need to convert the JSON back into an object with methods to use on the client side. Currently, I am using a static method for this conversion, but it's a manual process.

Is there a more efficient way to achieve this?

class Rectangle {
    constructor(public width: number, public height: number) { }
    public getArea(): number {
        return this.width * this.height;
    }

    public static fromPojo(pojo: any): Rectangle {
        if (pojo
            && pojo.width !== undefined
            && pojo.height !== undefined) {
                return new Rectangle(pojo.width, pojo.height);
            }
        throw new Error("Pojo is not a Rectangle");
    }
}

let rect = new Rectangle(10, 20);
console.log(rect.getArea()); // 200
let json = JSON.stringify(rect); // {"width":10,"height":20}

let rectFromJson = <Rectangle>JSON.parse(json);
console.log(rectFromJson.getArea()); // Error: rectFromJson.getArea is not a function

let rectFromPojo = Rectangle.fromPojo(JSON.parse(json));
console.log(rectFromPojo.getArea()); // 200

If a property gets added to the object, I have to make sure I update the fromPojo() method, making this tactic error-prone. Ideally, I want to find a more reliable and automated solution to handle this.

Update: The code below demonstrates the usage of Serializr, as suggested by Nick Uraltsev. This approach is less error-prone, but it does not retain the constructor parameters. It would be preferable to keep the constructor parameters intact.

import { deserialize, serializable, serialize } from "serializr";
class Rectangle {
    @serializable
    public width: number;
    @serializable
    public height: number;

    public getArea(): number {
        return this.width * this.height;
    }
}

let rect = new Rectangle();
rect.width = 10;
rect.height = 20;

let serJson = serialize(rect);
console.log(serJson); // { width: 10, height: 20 }

let reconstructedRect = deserialize(Rectangle, serJson);
console.log(reconstructedRect.getArea()); // 200

Answer №1

If you're searching for a solution, consider checking out the capabilities of Serializr. It appears to offer precisely what you're looking for.

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

ASP updatepanel textbox focusing - Working only with breakpoints, not without them

I've encountered a bizarre problem where my code functions perfectly with a breakpoint set, but when I remove the breakpoint, certain parts of the code fail to work. My goal is to have a textbox automatically select all text upon focus; it should foc ...

Creating a JavaScript equivalent of link_to with CSRF protectionIncorporating CSRF protection when

Attempting to send a patch request to this path: generate PATCH /tournaments/:id/generate/:groups/:finals_no/:prefinals/:two_g/:three_g/:four_g(.:format) tournaments#generate What makes it interesting is that the parameters after generate are retrieved ...

Leveraging Bluebird Promises in Node.js Development

I have a situation in my application where I need to read the contents of a file and then write them to another file. To achieve this, I am using bluebird promises. However, I would like some clarification on whether I am using promises correctly in my imp ...

Storing a JSON Array in Google Datastore: A Node's Guide

I attempted to save the following object in Google Datastore using NodeJS, but I'm receiving a 400 "bad request" error. { "_id":{ "$oid":"567e9e80067de880273095e0" }, "name":"Windows 10", "desc":"This is a Test", "isSel ...

Symfony is unable to access uploaded files from an AngularJS interface

For the past 3 days, I've been grappling with uploading files via AJAX to my Symfony2 application using AngularJS. I'm utilizing my Symfony app as an API to deliver data to my Angular front end. While I can successfully post text and other data, ...

Checkbox functionality included in the Kendo-Ui Angular 2 grid control

My Angular 2 KendoUI GRiD isn't keeping the checkbox checked state when the page changes. I'm using TypeScript for my Angular 2 scripts. ...

Storing values in an array when checkboxes are selected within an ng-repeat loop in AngularJS

I am facing a situation where I need to populate an array with values when a checkbox is checked within an ng-repeat iteration. <li ng-repeat="player in team.players"> <div class="row"> <div class="col-md-3 m-t-xs"> <inp ...

Identifying a vacant input field

My latest project involves creating a search bar that displays users whose first names start with the letter 'A' when the user presses 'A'. The functionality works as expected, but I've run into an issue when the search bar is empt ...

Send numerous data values using Jquery post()

After fetching 2 dates from a PHP script using $.post(), my goal is to split these results into two separate variables instead of combining them into one variable. Here is the jQuery code snippet: $.post('api/displayDBSetTimes.php', functio ...

Exploring the integration of React.Components with apollo-client and TypeScript

I am in the process of creating a basic React component using apollo-client alongside TypeScript. This particular component is responsible for fetching a list of articles and displaying them. Here's the code: import * as React from 'react' ...

Modifying the key of a JSON object can result in the alteration of other associated values as well

Overview: A JSON Object var JSON_OBJECT = []; has been defined as a global variable. [ { "user_id": "123", "AF": [ { "formula_type": 0, "lag": 0 } ], "Trend": [ { "is_active": 0 ...

Using async/await in React to retrieve data after a form submission

I am currently facing an issue with displaying data fetched from an API on the screen. My goal is to retrieve data when a user types something in a form and clicks the submit button. The error message I am encountering is: TypeError: Cannot read propert ...

Java implementation for arrays containing nested JSON objects

Struggling to figure out the structure for creating model classes to parse Json data from Alpha Vantage API. The format of the Json is as follows: { "Meta Data": { "1. Information": "Daily Time Series with Splits and Dividend Events", "2. Symbo ...

Tips for refreshing a webpage after switching screens

// I have implemented the code below to navigate from one screen to another, specifically the Home page. However, I am facing issues with the page refreshing or reloading when navigating to the home screen. None of the lifecycle methods are being called, e ...

Update various attributes of a div element using JavaScript

I have a progress bar in Bootstrap that receives data through a JavaScript function. Check out the progress bar below: <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" ...

How can I convert object into a Map instead of a String with Jackson databind?

Typically, when you need to convert an object into a JSON string, you would do something like the following: String json = objectMapper.writeValueAsString(myObject); But I'm curious if there is a way to directly serialize an object into a java.util.M ...

Is the return type of 'void' being overlooked in TypeScript - a solution to avoid unresolved promises?

When working in TypeScript 3.9.7, the compiler is not concerned with the following code: const someFn: () => void = () => 123; After stumbling upon this answer, it became apparent that this behavior is intentional. The rationale behind it makes sens ...

utilize forEach method in JavaScript to showcase images

I am having trouble displaying images in the "images" folder on my view. The path seems to be correct and there are no errors displayed in the browser console. Can someone please help me troubleshoot this? function Abstract() { let images = [...docu ...

"Python: Troubleshooting missing elements in headless mode with Selenium

Currently, I am using selenium to extract data from the Amazon search results page. In an effort to enhance efficiency, I decided to switch my scraping process to headless mode. However, I encountered an issue where certain page elements, like sponsored br ...

Buefy table in Vue with various row statuses

One interesting feature of Buefy tables is the ability to highlight rows with a specific color based on a variable in the row. :row-class="(row, index) => row.variable === x && 'is-info'"> In order to style the specific row class: <styl ...