我正在尝试从API请求中获取JSON响应,并将其填充到我的样式(类)中,该样式是使用下面列举的所有类中的自定义对象构建的。当我发出这样的请求时,我收到一个带有许多(超过1个)样式对象的JSON对象。
以下是我的search.component.ts中的类(模型,接口,我不确定):
class Make {
id: number;
name: string;
niceName: string;
}
class Model {
id: number;
name: string;
niceName: string;
}
class Year {
id: number;
year: number;
}
class Submodel {
body: string;
fuel: string;
modelName: string;
niceName: string;
}
class Categories {
EPAClass: string;
market: string;
primaryBodyType: string;
vehicleSize: string;
vehicleStyle: string;
vehicleType: string;
}
class Price {
baseMSRP: number;
baseInvoice: number;
deliveryCharge: number;
estimateTmv: boolean;
}
class Engine {
id: number;
name: string;
compressionRatio: number;
cylinder: number;
size: number;
displacement: number;
configuration: string;
fuelType: string;
horsepower: number;
torque: number;
totalValves: number;
manufacturerEngineCode: string;
type: string;
code: string;
compressorType: string;
}
class Transmission {
id: number;
name: string;
automaticType: string;
transmissionType: string;
numberOfSpeeds: number;
}
class OptionsDetail {
id: number;
description: string;
name: string;
equipmentType: string;
manufactureOptionName: string;
manufactureOptionCode: string;
price: Price;
}
class Options {
category: string;
options: OptionsDetail[];
}
class ColorChips {
primary: {
r: number;
g: number;
b: number;
hex: string;
};
secondary: {
r: number;
g: number;
b: number;
hex: string;
};
fabricType: string;
}
class ColorDetails {
id: number;
name: string;
manufactureOptionName: string;
manufactureOptionCode: string;
category: string;
colorChips: ColorChips;
}
class Color {
category: string;
options: ColorDetails[];
}
class MPG {
city: number;
highway: number;
}
class Style {
id: number;
name: string;
make: Make;
model: Model;
year: Year;
submodel: Submodel;
trim: string;
states: string[];
engine: Engine;
transmission: Transmission;
options: Options[];
colors: Color[];
drivenWheels: string;
numOfDoors: string;
squishVins: string[];
categories: Categories;
MPG: MPG;
manufacturerOptionCode: string;
我要做的是接受以下的json回复:
export class EdmundsAPIComponent {
data: Object;
loading: boolean;
constructor(private http: Http) {
}
makeRequest(): void {
this.loading = true;
this.http.request('https://api.edmunds.com/api/vehicle/v2/styles/101418796?view=full&fmt=json&api_key=REDACTED')
.subscribe((res: Response) => {
this.data = res.json();
this.loading = false;
console.log(this.data);
});
}
}
并将其填充到样式数组中。
我相信我需要为我的样式类创建一个构造函数,但是我不太确定如何用我给定的API数据点构造它(这些类匹配api响应'verbatim'。)
我不确定我是否需要所有类的构造函数。
此外,我不知道如何将api响应“推”到我的自定义“Style”模型中,以便从我的组件中操纵它的数据字段。
我想将这些类分成不同的文件以供我使用的所有组件 - 但是我不确定在哪里放置它们。
答案 0 :(得分:1)
我不确定我完全明白你想要什么。但是你想要解析被序列化为JSON的对象的声音吗?
对于您编写的复杂数据结构,看起来您希望使用代数数据类型对json进行反序列化。
也许你的情况有点矫枉过正了。你能展示数据的例子吗?