Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Equivalent of [JsonPropertyName] from C# in TypeScript

I need to deserialize some JSON response to my class defined in Angular. Let’s give example class:

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

But the JSON response looks like:

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

So while deserializing I want to map hub_url to hubUrl and so on. It’s easy to do in C# by using [JsonPropertyName] attribute, but I can’t find equivalent in Angular.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Or maybe its okay to have properties names like ‘hub_url_ etc?

>Solution :

you could go over the response and replace all characters after a underscore with its capitalized version and remove the underscore on the fly, basically a snake-to-camel-case 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;
}

You could also use the ‘class-transformer’ module (recomended):

npm i class-transformer

Then adapt your code like this:

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

And then use the plainToClass function provided by the class-transformer module to generate the Object with the JSON-response:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading