2017-06-15 86 views
3

我需要從Angular 4應用程序調用[POST] REST服務。其餘服務期望在請求正文中包含JSON。Angular 4 - 將JSON映射到模型,反之亦然

這我構建的角度,基於一些用戶輸入的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和類中的字段名稱不匹配。所以,角度不會知道val類型與valType相同。我無法將.ts文件中的變量名稱保留爲val-type,因爲它不是有效的變量名稱,因爲有' - '。

想要聽取專家的意見,在這種情況下最好的方法是什麼?我應該只是構建json而不用擔心類,還是有另一種方法來獲得這種強類型?

回答

3

您可以使用Json typescript decorater在發佈時序列化您的模型。

例如,聲明類照例:

export class SubPart { 
    @JsonProperty('val-type') 
    public valType: string; 
} 

填充模型

let jsonSubpart: Subpart = { 
    valType: userInput.valtype 
    } 

同時張貼模型

var json = serialize(jsonSubpart); 
相關問題