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.
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..."
});