我从远程REST服务器读取了一个JSON对象.此JSON对象具有typescript类的所有属性(按设计).如何将收到的JSON对象强制转换为类型var?
我不想填充一个typescript var(即有一个带有这个JSON对象的构造函数).它很大并且通过属性按子对象和属性跨子对象复制所有内容将花费大量时间.
更新:您可以将其转换为打字稿界面!
我做了很多研究,但我对我发现的东西并不完全满意.只是为了确定这是我的问题:什么是将JSON反序列化为TypeScript运行时类实例的最强大,最优雅的自动化解决方案?
说我上了这堂课:
class Foo {
name: string;
GetName(): string { return this.name };
}
Run Code Online (Sandbox Code Playgroud)
并说我有这个JSON字符串用于反序列化:
{"name": "John Doe"}
Run Code Online (Sandbox Code Playgroud)
获取名称设置为"John Doe"和GetName()方法的Foo类实例的最佳和最易维护的解决方案是什么?我非常具体地问,因为我知道很容易反序列化为纯数据对象.我想知道是否可以使用工作方法获取类实例,而无需进行任何手动解析或任何手动数据复制.如果无法实现全自动化解决方案,那么下一个最佳解决方案是什么?
我有一个关于Angular 5 httpClient的问题.
这是一个带有方法foo()的模型类,我希望从服务器接收
export class MyClass implements Deserializable{
id: number;
title: string;
deserialize(input: any) {
Object.assign(this, input);
return this;
}
foo(): string {
// return "some string conversion" with this.title
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的服务请求:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { MyClass } from './MyClass';
@Injectable({
providedIn: 'root',
})
export class MyClassService {
constructor(private http: HttpClient) {
}
getMyStuff(): Observable<MyClass[]> {
// this is where I hope …Run Code Online (Sandbox Code Playgroud) 我正在尝试将 API 响应转换为完全不同的 ViewModel,用于多个组件。
a) 一种解决方案是直接在 API 代理中映射/管道数据,但是如果我只想要普通的原始 API 数据,那么 API 代理不是很可重用。
b) 这种模型-适配器模式可能不起作用,因为在示例中,适配器创建了与 API 相同的数据对象类型。https://florimond.dev/blog/articles/2018/09/sumption-apis-in-angular-the-model-adapter-pattern/。我们下面的数据转换器,带来了完全不同的一个。
寻找任何其他好的解决方案。
常规API:
export class ProductService {
private readonly apiUrl = environment.baseUrl + '/api/CalculateProducts/';
constructor(private httpClient: HttpClient) { }
getProductData(
productValuationDtoRequest: ProductValuationDtoRequest
): Observable<ProductValuationResponse> {
return this.httpClient.request<ProductValuationResponse>('post', this.apiUrl,
{body: productValuationDtoRequest}
);
}
}
Run Code Online (Sandbox Code Playgroud)
数据转换器:
export class CalculateProductModelService {
constructor() { }
convertData(
productValuationResponse: ProductValuationResponse): CalculateCostModel {
const calculateProductModel: CalculateProductModel = {
valuationAttribute: productValuationResponse?.productValuationDetail[0]?.productValuationAttribute?.description,
livingAreaQuantity: productValuationResponse?.productValuationDetail[0]?.quantity,
livingAreaRate: productValuationResponse?.productValuationDetail[0]?.improvementUnitValue * 1.03,
livingAreaValue: productValuationResponse?.productValuationDetail[0]?.attributeTotalImprovementValue,
numberOfUnits: productValuationResponse?.numberOfUnits …Run Code Online (Sandbox Code Playgroud)