簡體   English   中英

如何從 Json 數據創建 TypeScript 類?

[英]How to create TypeScript class from Json data?

我正在使用 Angular 調用外部 API。 Json 數據的格式如下:

[
      {
        "AccessGroupsIdList": [],
        "FirstName": "Greg",
        "LastName": "Tipton",
        "LocationIdList": [],
        "PermissionProfile": {
          "Name": "Agent",
          "PermissionProfileId": {
            "ID": "xy678219-bd7c-103d-b56b-1f1234a85990"
          },
          "Type": 3
        },
        "ManagerName": "Gilchrist, George",
        "Status": true,
        "UserGroupID": {
          "ID": "00000000-0000-0000-0000-000000000000"
        },
        "UserGroupName": "ROOT",
        "UserId": {
          "ID": "4445cc66-819a-4da0-8fbf-d0bb8ce65941"
        }
      }
    ]

由於 json 數據是嵌套的,如何在打字稿中創建一個類來讀取它?

export class Employees
{
AccessGroupsIdList: string[];
FirstName: string;
LastName: string;
LocationIdList : number[];
PermissionProfile ??
ManagerName: string;
Status: boolean;
UserGroupID ??
UserGroupName : string;
UserId ??
}

請指導如果PermissionProfile, PermissionProfile 會單獨嵌套類嗎? 我如何聲明這些?

嘗試如下聲明 Typescript 類結構:

export class Employees
{
    AccessGroupsIdList: string[];
    FirstName: string;
    LastName: string;
    LocationIdList : number[];
    PermissionProfile: PermissionProfile;
    ManagerName: string;
    Status: boolean;
    UserGroupId: UserGroupID;
    UserGroupName : string;
    UserId: UserID;
}

export class PermissionProfile 
{
    name: string;
    permissionProfileId: PermissionProfileID;
    type: string;
}

export class PermissionProfileID
{
    id: string;
}
 
export class UserGroupID
{
    id: string;
}

export class UserID
{
    id: string;
}

我建議使用 Id 命名屬性名稱(例如使用UserGroupId )。 nametype類屬性名稱在 TypeScript 中有效(與 C# 語法不同)。

為了擴展 Andrew Halil 的回答,我將在您的定義中使用接口而不是類,因為似乎沒有涉及任何類方法; 您只是在描述從服務器返回的 JSON 對象的形狀

export interface Employee
{
    AccessGroupsIdList: string[];
    FirstName: string;
    LastName: string;
    LocationIdList : number[];
    PermissionProfile: PermissionProfile;
    ManagerName: string;
    Status: boolean;
    UserGroupId: ID;
    UserGroupName : string;
    UserId: ID;
}

export interface PermissionProfile 
{
    name: string;
    permissionProfileId: ID;
    type: string;
}

export interface ID
{
    id: string;
}
 

現在至於實現,我並沒有那么多地使用 Angular,但是你會做這樣的事情來輸入項目


async function listEmployees(): Promise<Employee[]> {
// Make a fetch call to the API endpoint
   const data = await fetch('https://some-api-endpoint.web/employees')
      // if the response comes back ok, return the JSON-ified response.
      .then(res => {
          if(res.ok) return res.json()
          return [];
      });
    // Instruct typescript that "data" is to be treated as an array of Employee elements.
    return data as Employee[]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM