Deserializing concrete types from an abstract list in TypeScript (serialized in JSON.NET)

I'm working with an API that returns an object containing a list of various concrete types that share a common base. Is there a way to automate the process of mapping these items to a specific Typescript interface model-type without having to manually map each one?

Is it possible to leverage the "$type" property that JSON.NET includes in the JSON object and automatically map it to a Typescript interface/model instance? Or is there another method that doesn't involve manual mapping?

Note: In my case, the .NET class namespace is removed during serialization from the API for client requests (e.g. { $type: 'Foo' } instead of { $type: 'MyApp.Models.Foo' })

Answer №1

If you are in need of class instances instead of plain objects, then you must traverse the object tree using reflection and recursively deserialize it.

Here is a basic outline:

class Person
{
    name: string;

    log()
    {
        console.log("Name: " + this.name);
    }
}

class Employee
{
    age: number;

    log()
    {
        console.log("Age: " + this.age);
    }
}

class DataObject
{
    items: (Person | Employee)[];
}

/** Type mappings. */
const types = {
    "DataObject": DataObject,
    "Person": Person,
    "Employee": Employee
};

const deserialize = <R = any>(instance: { $type: string }): R =>
{
    // Create instance of the class.
    const ctor = types[instance.$type];
    const obj = new ctor();

    // Assign/deserialize all properties of the object.
    for (const key in instance)
    {
        const val = instance[key];
        if (val == null)
        {
            obj[key] = val;
        }
        else
        {
            if (typeof val.$type == 'string')
                obj[key] = deserialize(val);
            else if (Array.isArray(val))
                obj[key] = val.map(item => item == null ? item : deserialize(item));
            else
                obj[key] = val; // Might be some standard type 🤷
        }
    }

    return obj;
}
const jsonData = {
    $type: 'DataObject',
    items: [
        { $type: "Person", name: "Alice" },
        { $type: "Employee", age: 30 },
    ]
};
const testObj = deserialize<DataObject>(jsonData);

testObj.items.forEach(item => item.log());

This will output correctly:

Name: Alice
Age: 30

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

Guide to aligning a component in the middle of the screen - Angular

As I delve into my project using Angular, I find myself unsure about the best approach to rendering a component within the main component. Check out the repository: https://github.com/jrsbaum/crud-angular See the demo here: Login credentials: Email: [e ...

The functionality of d3 transition is currently non-existent

I've encountered an issue with my D3 code. const hexagon = this.hexagonSVG.append('path') .attr('id', 'active') .attr('d', lineGenerator(<any>hexagonData)) .attr('stroke', 'url(#gradi ...

Angular 2 template can randomly display elements by shuffling the object of objects

I am working with a collection of objects that have the following structure: https://i.stack.imgur.com/ej63v.png To display all images in my template, I am using Object.keys Within the component: this.objectKeys = Object.keys; In the template: <ul ...

Observable - initiating conditional emission

How can I make sure that values are emitted conditionally from an observable? Specifically, in my scenario, subscribers of the .asObservable() function should only receive a value after the CurrentUser has been initialized. export class CurrentUser { ...

Easily Organize Your Data with Kendo React Grid: Rearrange Columns and Preserve Your Custom Layout

Currently, I am working on implementing a Kendo React grid with the option set to reorderable={true} for allowing column reordering. However, I am facing difficulty in determining how to save the new order of columns. Which event should I use to detect whe ...

Ways to modify the access control to permit origin on a specific API URL in React

https://i.stack.imgur.com/tqQwO.png Is there a way to modify the access control allow origin for a URL API? I keep encountering error 500 whenever I try to load the page. After logging in, I included this code snippet: const options = { header ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

Can classes be encapsulated within a NgModule in Angular 2/4?

Looking to organize my classes by creating a module where I can easily import them like a separate package. Take a look at this example: human.ts (my class file) export class Human { private numOfLegs: Number; constructor() { this.numOfLegs = 2 ...

"Encountering a 500 error on Chrome and Internet Explorer while trying to sign

I am currently working on an ASP.NET Core application that handles identity management through Azure AD B2C using the ASP.Net Core OpenID Connect. The front end is developed using AngularJS 2 with TypeScript. In my Logout function, the user is redirected t ...

Tips for refreshing the value of a dependency injection token

When using Angular dependency injection, you have the ability to inject a string, function, or object by using a token instead of a service class. To declare it in my module, I do this: providers: [{ provide: MyValueToken, useValue: 'my title value& ...

Exploring Angular 2: Incorporating multiple HTML pages into a single component

I am currently learning Angular 2 and have a component called Register. Within this single component, I have five different HTML pages. Is it possible to have multiple templates per component in order to navigate between these pages? How can I implement ro ...

Having trouble assigning a value of `undefined` to a TextField state in React hook

I am in need of setting the initial state for a TextField date to be undefined until the user makes a selection, and then allowing the user an easy way to reset the date back to undefined. In the code snippet below, the Reset button effectively resets par ...

Coding with Angular 4 in JavaScript

Currently, I am utilizing Angular 4 within Visual Studio Code and am looking to incorporate a JavaScript function into my code. Within the home.component.html file: <html> <body> <button onclick="myFunction()">Click me</button> ...

The issue with launching a Node.js server in a production environment

I'm currently facing an issue when trying to start my TypeScript app after transpiling it to JavaScript. Here is my tsconfig: { "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "baseUrl": "src", "target": " ...

Angular directive to delete the last character when a change is made via ngModel

I have 2 input fields where I enter a value and concatenate them into a new one. Here is the HTML code: <div class="form-group"> <label>{{l("FirstName")}}</label> <input #firstNameInput="ngMode ...

What improvements can I make to enhance my method?

I have a block of code that I'm looking to clean up and streamline for better efficiency. My main goal is to remove the multiple return statements within the method. Any suggestions on how I might refactor this code? Are there any design patterns th ...

Using the hash(#) symbol in Vue 3 for routing

Even though I am using createWebHistory, my URL still contains a hash symbol like localhost/#/projects. Am I overlooking something in my code? How can I get rid of the # symbol? router const routes: Array<RouteRecordRaw> = [ { path: " ...

What could be the reason for the failure of my class isInstance() check

Do you see any issues with the object being an instance of ChatRoom? Let me know your thoughts. Class: export class ChatRoom { public id?: number; public name_of_chat_room: string; public chat_creator_user_id: number; public chat_room_is_active: 0 ...

How can I turn off the draggable feature for a specific element in react-beautiful-dnd?

Currently, I am implementing a drag and drop functionality using TypeScript with react-beautiful-dnd. The goal is to allow users to move items between two containers - one containing user names and the other labeled "Unassigned". Here is a snapshot of the ...

Function 'Once' in Typescript with Generics

Currently, I am utilizing a feature called Once() from FP. In TypeScript, I need to define the types for this function but have been struggling with the implementation. Here's what I have attempted so far: const once = <T, U>(fn: (arg: T) => ...