简体   繁体   中英

JSON to TypeScript in Angular

I have an http service in angular which makes call to web api to get JSON data which needs to be deserialized to typescript (.ts) objects. The name of key in JSON (ie "Property") is not matching to what I have in typescript (ie "property") - meaning JSON data is Uppercase and typescript is lowercase. Is there a mapping function with http calls in angular where I can deserialize the json to typescript?

Example JSON coming back from web api

"Packages": [
      {
          "IsESignAllowed": false,
          "IsEnabled": true,
          "Name": "Brokerage Accounts Package",
          "PackageId": 2
      }
]

Associated .ts file on Angular

export class Package {
    public isESignAllowed: boolean;
    public isEnabled: boolean;
    public name: string;
    public packageId: number;
}

You can add some serialisation functions to your Package class in typescript, this will allow you to map the JSON object from the server to a new Package object in TS.

As mentioned, it would be best to keep standard camel case convention everywhere - and have the server send JSON with lowercase property names, however, if this is not possible, this can still be handled in your serialisation functions.

export class Package {
    public isESignAllowed: boolean;
    public isEnabled: boolean;
    public name: string;
    public packageId: number;

    static fromJson(jsonObj: any) {
        const newPackage = new this();
        newPackage.isESignAllowed = jsonObj.IsESignAllowed;
        newPackage.isEnabled = jsonObj.IsEnabled;
        newPackage.name = jsonObj.Name;
        newPackage.packageId = jsonObj.PackageId;
        return newPackage;
    }

    public toJson(): any {
        const jsonObj: any = {};
        jsonObj.IsESignAllowed = this.isESignAllowed;
        jsonObj.IsEnabled = this.isEnabled;
        jsonObj.Name = this.name;
        jsonObj.PackageId = this.packageId;
        return jsonObj;
    }
}

Once you have received the JSON from the server, you can now map the array of packages over the new Package.fromJson() function, to create a list of Package objects.

const packages = serverResponse.Packages.map(packageJson => Package.fromJson(packageJson));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM