Similar to [JsonPropertyName] in C#, but for TypeScript

Need help deserializing JSON response into a class defined in Angular. Let's use the example class below:

export class ChatHubInfo {
  hubUrl: string = undefined!
  accessToken: string = undefined!
}

However, the JSON response is structured differently:

{
   "hub_url": "https://localhost:8080/",
   "access_token": "v4.public.eY..."
}

During deserialization, I need to map hub_url to hubUrl, and so on. In C#, I can easily achieve this using the [JsonPropertyName] attribute, but I'm unsure of the equivalent in Angular.

Is it acceptable to have property names like 'hub_url', etc?

Answer №1

If you want to convert snake_case to camelCase in a string, you can use the following function:

function snakeToCamel(str: string): string {
    return str.replace(/_([a-z])/g, (_, group1) => group1.toUpperCase());
}

function convertKeysToCamelCase(obj: Record<string, any>): Record<string, any> {
    const result: Record<string, any> = {};

    for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            const camelKey = snakeToCamel(key);
            result[camelKey] = obj[key];
        }
    }

    return result;
}

Alternatively, you can use the 'class-transformer' module for easier conversion:

npm i class-transformer

Then modify your code as shown below:

import { Expose } from "class-transformer"
export class ChatHubInfo {
    @Expose({name: "hub_url"})
    hubUrl: string = undefined!
    
    /*...etc...*/
}

Finally, you can use the plainToClass function from the class-transformer module like this:

import { plainToClass } from "class-transformer"
const chatHubInfo = plainToClass(ChatHubInfo, {
    "hub_url": "https://localhost:8080/",
    "access_token": "v4.public.eY..."
});

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 dynamically altering the data type of an object in Angular depending on a certain condition

I'm currently in the process of developing an online store and facing challenges with integrating a dynamic form system that can adapt based on the type of product being added to the store. For instance, if I select the 'Clothing' category, ...

What is the best way to pass the token received from a post request to a get request using Angular?

After receiving a token in a POST request, I need to pass it in a GET request. To achieve this, I store the token obtained from the POST request in one. The interesting thing is that in GetToken, I display it on the console and it appears correctly indicat ...

Explore the intricacies of RxJS catchError

I am a beginner in RxJS and I am struggling to understand how the parameters are passed in this code snippet: import { catchError, map, Observable, of } from 'rxjs'; let obs$ = of(1,2,3,4,5); obs$.pipe( map(n => { if (n === 4) { ...

Retrieve information from a JSON file according to the provided input

Can someone help me fetch data based on user input in JavaScript? When the input is 'Royal Python', I'm supposed to retrieve details about it. However, the code provided gives an error stating 'The file you asked for does not exist&apo ...

Exploring the symfony2 shop's read-only settings

How can read-only configuration be stored effectively in Symfony? I have a JSON file containing name/description pairs located in a bundle's resource directory that I want to access in my controllers and views without storing them in the database. A ...

Unable to find solutions for all parameters in AngularFirestoreDocument: (?, ?)

I have integrated Angular 11 with Firebase for authentication and Firestore for data collection. However, I encountered an error message Can't resolve all parameters for AngularFirestoreDocument: (?, ?). How can I resolve this null injector issue? On ...

Enhance the Nuxt 3 experience by expanding the functionality of the NuxtApp type with

When I include a plugin in my NuxtApp, it correctly identifies its type. https://i.stack.imgur.com/UFqZW.png However, when I attempt to use the plugin on a page, it only displays the type as "any." https://i.stack.imgur.com/hVSzA.png Is there a way for ...

Setting up Zurb Foundation in a VueJS TypeScript project: Step-by-step guide

I'm currently facing a challenge involving the integration of Zurb Foundation v6.5.3 into a VueJS project that is TypeScript-based and was created using @Vue/CLI. The project already includes jQuery type definitions. In the code snippet below, you can ...

Why isn't this Java page displaying the data I need from this Json file?

Hey friends, I'm facing a major issue with my project. I've made an OkHttp request and received a response from the server successfully. However, I'm unable to display the data on my model item in XML and listview (the required view). Whenev ...

What is the best method for obtaining user data when additional custom data is stored in Cloud Firestore?

Storing the user's information such as email, name, age, phone number, and uid is essential. In the user.model.ts file: export interface User { uid: string, name: string, email: string, phoneNumber: string, age: string } In auth. ...

Is it feasible to securely remove an item from an array within an object without the need for any assertions in a single function?

My interest in this matter stems from curiosity. The title may be a bit complex, so let's simplify it with an example: type ObjType = { items: Array<{ id: number }>; sth: number }; const obj: ObjType = { sth: 3, items: [{ id: 1 }, { id: 2 } ...

What is the best way to remove a void type from a union type?

Hey there everyone, I have a custom generic type called P that is defined as P extends Record<string, unknown> | void I am looking to create an exists function export class Parameters<P extends Record<string, unknown> | void> { p ...

Looking for assistance with JSON and jQuery?

Hey there! I'm currently working on pulling in a jsonp feed using jQuery and formatting a widget with the data. It's almost there, but I'm facing an issue trying to set the value of my link <a href=""> as "item.url" from my jsonp respo ...

How can I process a data retrieval request in a Laravel controller if someone asks for information from my applications?

The request will be in JSON format, as follows: { "app_id": 1234, "app_key": "our_app_key", "bus_id": 67, "data": [{ "seat_id": 1 }, { "seat_id": 2 }] This is the content of my routes.php file: Route::get('getBookingSeats', 'Selec ...

Error encountered: Could not find the specified file or directory, 'resultsCapturer.js:.will-be-removed-after-cucumber-runs.tmp'

I'm currently working on automating an Angular 4 application. Whenever I execute "protractor config.js" SCENARIO 1: If the format option in my config.ts file looks like this: format: ['json:../reporting/results.json'] An error message is ...

Calculate the total number of seconds from an ISO8601 duration with TypeScript by utilizing the date-fns library

Given an ISO8601 duration string like "PT1M14S," I am looking to convert it to seconds as an Integer using the date-fns library in TypeScript. ...

Transmission of JSON to a C# controller via AJAX results in a Count value of zero in .NET 7

Whenever I attempt to send a JSON object to my controller, the parameter isn't being received. This is the JavaScript code snippet: var input = document.getElementById("input"); input.addEventListener('change', function () { const read ...

The attribute 'sandwiches' cannot be found within the data type 'string'

In my app, I require an object that can store strings or an array of strings with a string key. This object will serve as a dynamic configuration and the keys will be defined by the user, so I cannot specify types based on key names. That's why I&apos ...

What is the best way to retrieve a value from a JSON object using AngularJS?

Using nodeJS, the server sends a JSON object to the controller: data = { "question": "theQuestion", "answer": "theAnswer" }; res.json(data); In the controller, I attempt to manipulate the variable as follows: data = QA.get(); $scope.q = data[que ...

Mastering the use of npm and sails to create HTML-PDF files effortlessly

UPDATE: I am simplifying my question and will address any other concerns in separate posts if necessary. The initial post was too lengthy, hoping for a straightforward guide on utilizing sails to its fullest potential. Apologies. To begin with, my knowled ...