我需要从 Angular 4 应用程序调用 [POST] REST 服务。其余服务需要请求正文中的 JSON。
我在 Angular 中构建的 JSON,基于一些用户输入看起来像
{
"val-type": "prop",
"val-name": "prop1",
"op-ter": "DIFF",
"value": "Unknown",
"match-twice": false,
"case-sensitive": false
}
在我的代码中,我将这个 json 创建为
let jsonSubpart = {
"val-type": userInput.valtype,
"val-name": userInput.valname,
"op-ter": userInput.opter,
"value": userInput.val,
"match-twice": false,
"case-sensitive": false
}
我希望我可以为这个结构创建一个模型,以确保遵守 json 结构。所以,我继续创建一个 model.ts 文件,如下所示
export class SubPart {
public valType: string;
public valName: string;
public opTer: string;
public value: string;
public matchTwice: boolean = false;
public caseSensitive: boolean = false;
constructor(valType: string, valName: string, opTer: string, value: string,
matchTwice: boolean, caseSensitive: boolean) {
this.valType=valType;
this.valName= valName;
this.opTer=opTer;
this.value = value;
this.matchTwice=matchTwice;
this.caseSensitive = caseSensitive;
}
}
我的想法是在构建 json 时使用这个模型 -
import { Subpart} from './subpart.model.ts';
let jsonSubpart: Subpart = {
"val-type": userInput.valtype,
"val-name": userInput.valname,
"op-ter": userInput.opter,
"value": userInput.val,
"match-twice": false,
"case-sensitive": false
}
但是,这将不起作用,因为 json 中的字段名称和类不匹配。所以,angular 不知道 val-type 和 valType 是一样的。我不能将 .ts 文件中的变量名保留为 val 类型,因为它不是有效的变量名,因为有一个“-”。
想听听专家的意见,在这种情况下最好的方法是什么?我应该只构建 json 而不必担心类,还是有另一种方法来获得这种强类型?
最佳答案
您可以使用 Json typescript decorater在发布时序列化您的模型。
例如,照常声明类:
export class SubPart {
@JsonProperty('val-type')
public valType: string;
}
填充模型
let jsonSubpart: Subpart = {
valType: userInput.valtype
}
并在发布模型时
var json = serialize(jsonSubpart);
关于json - Angular 4 - 将 JSON 映射到模型,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44558164/