【问题标题】:Strict data type for json filejson文件的严格数据类型
【发布时间】:2023-04-10 05:10:01
【问题描述】:

当我从 json 中获取数据时,我首先创建一个类并定义我在 json 中获得的所有变量,以获得严格的数据类型,例如我的 json 文件是

 {"fname":"Mark","lname":"jhony"}

所以在 Angular 中,我制作了这样的课程

export class user{

 fname: string;
 lname : string;
}

我很困惑如何为以下 json 数据创建类

{"fname":"Mark","lname":"jhony",
 "parcels":[
   {
    "parcelId":123,
    "parcelName :"asd",
    "parcelItems:[
       { 
        "itemId":2,
        "itemName":"perfume"
       },
       { 
         "itemId":4,
         "itemName":"soap"
       }
     ]
]}

我试图在类中添加数组,但没有得到在 angularjs 中处理它的最佳方法。

【问题讨论】:

    标签: angularjs json typescript


    【解决方案1】:

    这会起作用。

    export interface ParcelItemType {    
        itemId: number;
        itemName: string;
    }
    
    export interface ParcelType {
        parcelId: number;
        parcelName: string;
        parcelItems: ParcelItemType[];
    }
    
    export interface YourType {
       fname: string;
       lname: string;
       parcels: ParcelType[];
    }
    

    【讨论】:

      【解决方案2】:

      通常您会使用接口来表示原始值的数据结构,例如:

      interface ParcelItem {
        itemId: number;
        itemName: string;
      }
      interface Parcel {
        parcelId: number;
        parcelName: string;
        parcelItems: ParcelItem[];
      }
      interface User {
        fname: string;
        lname: string;
        Parcels: Parcel[];
      }
      

      根据您获取 JSON 和解析它的方式,您可以指定要使用的接口。最简单的例子是:

      const user = JSON.parse(userJson) as User;
      

      如果您想将一个类用于相关的数据操作方法,您必须使用构造函数实例化该类。这可能看起来像:

      const userValues = JSON.parse(userJson);
      const user = new User(userValues);
      

      【讨论】:

      • 需要注意的重要一点:这不会以任何方式验证 JSON。这意味着稍后您可能会收到运行时错误,例如 lname 未定义。键入仅在编译时验证 TypeScript 代码与其自身是否一致。对运行时一无所知。作为一个 TypeScript 新手,我必须让一位同事向我解释这一点,直到我明白这种模式中没有 validation。他还提到人们使用其他一些工具指定他们的 JSON,然后生成 TypeScript 类型。
      • 这里有几个答案,如果还需要 runtime 验证该怎么办:stackoverflow.com/questions/33800497/… 还有另一个问题:stackoverflow.com/questions/14425568/…
      猜你喜欢
      • 2012-01-24
      • 2012-04-21
      • 1970-01-01
      • 2022-01-26
      • 2021-06-25
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多