Working with Angular 4 and Typescript: Transforming JSON data with json2typescript key mapping

Apologies for the confusion in my previous explanation. Let me clarify my question:

In my Angular 4 application, I am using json2typescript to handle JSON to object conversion. However, I am facing an issue where the class structure I have defined does not match the structure of the JSON response from an external API. Here is an example:

Customer {
  @JsonProperty('idCardNumber', String)
  idCardNumber: string = undefined;
  @JsonProperty('rolInfo.name',String) 
  name: string = undefined;
  @JsonProperty('rolInfo.surname',String) 
  surname: string = undefined;  
}

JSON response from External API:

 {
   "idCardNumber": "08989765F",
   "rolInfo": {
      "name": "John"
      "surname: "Smith"
   }
 }

My goal is to map the above JSON structure to my Customer object without altering my class structure. I have attempted to include 'rolInfo.name' in the JsonProperty but it did not produce the desired outcome.

Answer №1

Revamp your Customer class to resemble the following structure

Customer {
  @JsonProperty('idNumber', String)
  idNumber: string = undefined;

  @JsonProperty('roleDetails', Any) 
  roleDetails: any = {}; // Handle undefined in getter/setter method

  get fullName(): string {
      return this.roleDetails['fullName'];
  }

  set fullName(value: string) {
      this.roleDetails['fullName'] = value;
  }

  get age(): string {
     return this.roleDetails['age'];
  }

  set age(value: string) {
      this.roleDetails['age'] = value;
  }
}

Implement these changes and it should work as expected

Answer №2

It appears that the JSON response is already well-formatted, eliminating the need for conversion. I suggest developing models to facilitate serialization and deserialization for API calls and to bind the response data to those models.

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 efficiently handling state across various forms in separate components using only one save button within a React-Redux application

I am currently developing an application that combines a .NET Core backend with a React frontend, using React Hook Form for managing forms. Unlike typical single-page applications, my frontend is not built in such a way. On a specific page of the applicat ...

Acquire data for a designated key from the complete JSON structure using Java

Here is the structure of my JSON response: { "status": true, "responseData": { "category": "Seeds", "image": "https://s3.ap-south-1.amazonaws.com/agrostarcatalog/static/Seeds.jpg", ... ], "id ...

Error encountered in Jest mockImplementation: Incompatible types - 'string[]' cannot be assigned to 'Cat[]' type

Recently, I've been writing a unit test for my API using Jest and leveraging some boilerplate code. However, I hit a snag when an error popped up that left me scratching my head. Here is the snippet of code that's causing trouble: describe(' ...

Typescript controller inheritance leading to Error: $injector:unpr Unknown Provider due to minification

LATEST UPDATE: 2019/07/16 The issue I am facing is actually a result of misusing $inject. Instead of declaring it as private $inject in api-service.ts, it should have been public static $inject = [...]. During the minification process, explicit injection ...

What prevents TypeScript from allowing an async function to return a combination of type T or Promise<T>?

During the development of my API in typescript, I encountered a situation where some controller actions can be synchronous while others cannot. To address this issue, I decided to specify a response type as follows: type ActionResult =IHttpActionResult | ...

Tips on separating keys and values in a JSON string using Swift 3

Here is a JSON string that I have: { "messages": null, "data": [ { "id": 27, "key": "ABC", "value": "5", "description": "Hi all" }, { "id": 28, "key": ...

Customize the style of Angular Material within an Angular component

In my Angular component, I am utilizing Material 2's <md-input-container>. I am looking to customize a specific class, such as .mat-input-wrapper, that is originally defined in Angular Material. However, my intention is for this customization to ...

What would be the counterpart of setLocale in Yup for the zod library?

How can I set default custom error messages for Zod validation? If I want to use i18n for error messages in Yup, I would do the following: import { t } from "i18next"; import * as yup from "yup"; import "./i18next"; yup.setL ...

Encountering a Newtonsoft.json issue while working on Xamarin Studio development

Hey everyone, I'm encountering an error while debugging my application. I'm trying to retrieve data from an SQL database and format it into a JSON string. My goal is to create an array of elements (A) containing their information (B1)(B2)(B3)(B4) ...

Issue: The component factory for GoogleCardLayout2 cannot be located

Recently I've been working on an Ionic 3 with Angular 6 template app where I encountered an issue while trying to redirect the user to another page upon click. The error message that keeps popping up is: Uncaught (in promise): Error: No component fac ...

Updating form values using ngModel in Angular 6

After upgrading from Angular 5 to 6, I attempted to update my form: In Angular 5, I had: <select [ngModel]="toto" (ngModelChange)="onChange($event)" <option *ngFor="let toto of totos" [ngValue]="toto.id">{{toto.libelle}}</option ...

Converting Excel files to JSON format

Can anyone tell me if it's possible to convert Excel to JSON? If so, what is the required structure of the Excel file for this conversion to work? Is there a specific application or tool that can help with this process? I have a JSON structure avail ...

How can you dynamically disable a Menu Item in Angular?

Struggling to implement a functional menu component that allows for disabling specific menu items without cluttering the main application code with excessive menu logic. Is there a way to achieve this without resorting to frequent refreshes or complicated ...

Encountering a runtime exception when using Immutables with Retrofit after receiving an error from the server

When the server returns a 101 error, a runtime exception is thrown stating "Failed to invoke public ... TestResponse() with no args". The root cause of this issue is the failure to deserialize the JSON. How can I handle an error object instead of the "Test ...

Encountering an issue while developing a Discord bot using TypeScript

Hello, I'm currently working on creating a nick command for my discord bot in TypeScript, but I encountered an error. Here is the issue: Error: Expression expected.ts (1109) When I replace const mentionedMember = message? message.mentions.members? ...

How to access a component attribute in a JavaScript library method in Angular 8

Within my Angular project, I am utilizing Semantic UI with the code snippet below: componentProperty: boolean = false; ngOnInit() { (<any>$('.ui.dropdown')).dropdown(); (<any>$('.ui.input')).popup({ ...

Each time the Angular Material autocomplete is used, it will trigger an API call to retrieve and

Whenever two letters are typed into the input field, I need to trigger an API call that displays a dropdown. If one more letter is typed, another API call should be made. My issue lies in dynamically binding and changing the API endpoint based on the searc ...

Navigating through a duo of dictionaries in Python

I am a Python novice with limited experience, so please excuse me if this is a basic question. My task involves reading multiple Json files and extracting certain values to store in two separate dictionaries. I want to display the results in the format be ...

Storing a variable in Cypress with Typescript for use in the afterEach teardown step

Throughout my test cases, I store data in a variable to be used consistently. The variable maintains its value until the very end of the test, but when trying to access it in the @afterEach teardown function for global clean up, it appears empty. It seems ...

Encountering a 400 error while making a Python request that involves

Below is the code I am using to register a user through an API endpoint: import argparse import requests import ConfigParser import json import sys import logging # Configuration Parameters env = 'Pre_internal' Config = ConfigParser.ConfigPar ...