Type error arises when attempting to map from JSON to TypeScript

I am currently working on mapping a list of .Net objects to my Angular frontend using Web Api 2. Depending on the circumstances, these objects and their properties may be an Employment reference, Assignment reference, or an Assignment organization unit reference.

Here is an illustration of how the list of objects can appear, with one AssignmentHolder that could belong to any of those three classes and a list of DependentEntities that could also be from one of those three classes. https://i.sstatic.net/etjpb.png Below is how they are structured in my Angular application:

This is the object that contains them:

@JsonObject('AssignmentListItem')
export class AssignmentListItem {
@JsonProperty('AssignmentHolder')
AssignmentHolder: any = undefined;

@JsonProperty('DependentEntities')
DependentEntities: any = undefined;

@JsonProperty('AssignmentRoles', [AssignmentRole])
AssignmentRoles: AssignmentRole[] = undefined;

@JsonProperty('NumberOfDependentEntities', Number)
NumberOfDependentEntities: Number = undefined;

@JsonProperty('IsInherited', Boolean)
IsInherited: boolean = undefined;
}

These are the different classes:

@JsonObject('ReferenceBase')
export class ReferenceBase {

@JsonProperty('OrganizationRegistrationNumber', OrganizationRegistrationNumber)
OrganizationRegistrationNumber: OrganizationRegistrationNumber = undefined;

@JsonProperty('IsIncomplete', Boolean)
IsIncomplete: Boolean = undefined;

@JsonProperty('SortingName', String)
SortingName: string = undefined;
}

-------

@JsonObject('EmploymentReference')
export class EmploymentReference extends ReferenceBase {

@JsonProperty('NationalCivicRegistrationNumber', String)
NationalCivicRegistrationNumber: NationalCivicRegistrationNumber = undefined;

...

-----

@JsonObject('AssignmentReference')
export class AssignmentReference extends ReferenceBase {

...

------

@JsonObject('AssignmentOrganizationalUnitReference')
export class AssignmentOrganizationalUnitReference extends ReferenceBase {

...

These are the objects I aim to map depending on the content in the assignment list.

This is a custom DTO for utilizing a custom converter:

@JsonObject('AssignmentsDto')
export class AssignmentsDto {

...

And this is the JsonCustomConverter used:

@JsonConverter
export class ObjectConverter implements JsonCustomConvert<AssignmentListItem[]> {

...

Finally, here is the Assignment Api Service where the converter is applied:

    // GET LIST OF ASSIGNMENTS

...

private convertData(res: Response) {

...

The error displayed in the console is:

A fatal error has occurred in JsonConvert. The JSON object failed to map to the JavaScript class "AssignmentsDto" due to a type error. Class property: AssignmentList Expected type: undefined JSON property: AssignmentList JSON type: [object, object, object, object, object]

Answer №1

To resolve this issue, I ensured that each property from the JSON object was correctly mapped to the TypeScript classes. In the AssignmentsDto, I included an additional object property and converter:

@JsonProperty('AssignmentList',[AssignmentListItem], ObjectConverter) AssignmentList: AssignmentListItem[] = undefined;

I trust this solution can benefit others!

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

What is the best way to display JSON using javascript?

I'm struggling with printing the results of a json object from a php query into javascript. The structure of the query results is as follows: {"points": [{"lat":40.766696929932,"long":-73.990615844727}, {"lat":40.688514709473,"long":-73.964759826 ...

Mastering the art of handling errors with Javascript Promises

Through thorough research and some assistance, I have managed to create and annotate code that I believe will enhance the comprehension of Javascript Promises for individuals. However, I encountered a puzzling issue when attempting to trigger an error by ...

Tips for determining data type in TypeScript without using the 'instanceof' operator

Attempting to upgrade a basic custom Link component in React to TypeScript has been a challenge. Below is the initial code for the simple Link component written in JavaScript: import React from "react"; import { Link as RouterLink } from "r ...

Tips for creating type-safe expressions for @Input() in Angular 2 and above?

What's the best way to create a function using @Input() in an Angular component? For instance, when defining a method that should return a boolean value: @Input callback: //(only allow methods with boolean return value) @Input callback: Function // ...

finding the adjacent li element using the document.(property)

Utilizing a pub/sub solution named ably.io for real-time data updates, I have implemented a method that assigns dynamic ids to each ngFor listing. This allows me to easily identify and update the values received from ably.io subscribe. document.getElement ...

Mastering the concept of promise chaining through this straightforward example

I'm struggling to implement a logic where I need to compare the user's password to a given password and handle different scenarios based on the comparison result. Here's what I need to achieve: If the user doesn't exist, return undefi ...

Tips on modifying JSON information from various collections of key-value pairs

What is the best way to manipulate JSON data by changing values from multiple key-value pairs in Java? ...

NextJS API routes consistently provide a status code of 200 upon execution

I am new to the concepts of Next.js, and I recently encountered an issue while attempting to fetch data from an API. The API is designed to check if a user session exists (i.e., if the user is logged in) and then returns a JSON response through a GET reque ...

the process of triggering animation to start automatically when a button is clicked in Web Development

I'm looking to create a React component that triggers an animation when clicked. I have a few options in mind: If the props are changed in the middle of the animation, it should restart the animation. The props can be changed by clicking a button on ...

Creating a List of Properties from a JSON Object in C#

Can anyone help me with building a property list that includes the property path of a JSON object? I am not familiar with the structure of the JSON or the keys that could be present. I am interested in extracting the keys at all levels (excluding the valu ...

Can a monorepo be organized into multiple levels? (Question regarding tooling and structure)

Currently in the process of researching how to transition my repositories into a monorepo and further segment the codebase by early 2023. I am utilizing TypeScript I have multiple servers that I plan to break down into microservices for easier development ...

The 'event' parameter is being implicitly assigned an 'any' type

I'm currently utilizing TypeScript within an Electron application but I am encountering the following error message: Parameter 'event' implicitly has an 'any' type.ts(7006) Below is the code snippet in question. Any suggestions ...

What is the result of using `X ? A : B` in typescript?

type TestAny = any extends 'a' ? 1 : 2 // => 1 | 2 why??? how to interpret? type TestUnknown = unknown extends 'a' ? 1 : 2 // => 2 type TestStringA = 'a' extends 'a' ? 1 : 2 // => 1 type SomeUnion = ' ...

Developing a custom HTTP request class in Angular 2 and its exporting capabilities

I have created a simple HTTP requests class using Angular 2: http-handler.ts import {Http, Headers, RequestOptions} from 'angular2/http' import {Injectable} from 'angular2/core'; import 'rxjs/add/operator/toPromise'; @Injec ...

Creating JSON data in PHP is a straightforward process that involves encoding

I am looking to generate a JSON output that looks like this: { "id": "c200", "name": "Aneesh", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86e7e8c6e1ebe7efeaa8e5e9eb">[email protected]</a> ...

Is it possible to have Ajax.BeginForm respond with JSON and seamlessly refresh the form without manual intervention?

My goal is to utilize DataAnnotation for validation on my model view and to trigger an action using Ajax.BeginForm or similar feature. The desired outcome is for the action to return JSON that will automatically update the form. In my current code, I am s ...

When it comes to Typescript interfaces, subsequent fields are not overloaded or merged

So I've been exploring interfaces in TypeScript and their ability to merge different types, but I ran into a hiccup while transpiling my script. Here's where things went wrong in my interface: export interface StoreConfig extends Document, TimeS ...

What is the reason for this basic JSON encoding not functioning properly?

I am facing an issue with a PHP page that is generating a JSON object. I have another page using the jQuery library and trying to access this object, but it's not working as expected. Instead of 'inside_ok', I see the message 'inside_nk ...

Exploring the functionality of angular reactive forms in creating intricate JSON structures

After numerous attempts to resolve the issue on my own, I am reaching out to an Angular developer for assistance. My goal is to display a JSON object in the UI: Here is the JSON Object : items={"departure":"New York","arrival":"California","stations":[ ...

What is the best way to set the typing of a parent class to the child constructor?

I am seeking a method to inherit the parameter types of a parent's constructor into the child's constructor. For example: class B extends A { constructor (input) { super(input); } } I attempted the following: class B extends ...