当我从 json 获取数据时,我首先创建一个类并定义在 json 中获取的所有变量,以实现严格的数据类型,就像我的 json 文件一样
{"fname":"Mark","lname":"jhony"}
所以在 Angular 上我让类(class)像这样
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 中处理它的最佳方法。
最佳答案
通常,您会使用接口(interface)来表示原始值的数据结构,例如:
interface ParcelItem {
itemId: number;
itemName: string;
}
interface Parcel {
parcelId: number;
parcelName: string;
parcelItems: ParcelItem[];
}
interface User {
fname: string;
lname: string;
Parcels: Parcel[];
}
根据您获取 JSON 并解析它的方式,您可以指定要使用的接口(interface)。最简单的例子是:
const user = JSON.parse(userJson) as User;
如果您想使用一个类来实现数据操作的关联方法,则必须使用构造函数实例化该类。这可能看起来像:
const userValues = JSON.parse(userJson);
const user = new User(userValues);
关于angularjs - json 文件的严格数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52591847/