[英]Typescript: How to deserialize JSON object with private variables?
[英]Mapping JSON String/JS object to Typescript class with private attributes
這是一個帶有暴露但不可編輯的屬性的typescript類:
export class Category {
private _id: number;
constructor(id: number){
this._id = id;
}
public get id(){
return this._id;
}
}
我想從這樣的JSON映射它:
{ id: 1 }
這里有一些明顯的問題:
Object.assign(new Category(), jsonObject)
,但是,這不起作用,因為Cannot set property id of #<Category> which has only a getter
我想要避免的是為每個類編寫自定義映射邏輯,使用私有屬性,我嘗試了一些其他解決方案和庫,但是對我的情況不起作用,它們都引用了只有公共屬性的類
我甚至不知道我的要求是否可以實現,所以如果不是這樣,那么我將“投降”使用只有公共屬性的類
這里的錯誤觀念是你需要一個getter / setter來管理可見性。 無論您做什么,都無法阻止代碼訪問和修改id
。 但是,您可以告訴IDE(以及使用它的開發人員)他只能使用readonly
修飾符讀取/獲取屬性,這會將您的代碼簡化為:
export class Category {
readonly id: number;
}
Noe readonly
事件只存在於編譯時,並且在運行時沒有任何影響。 您的IDE將阻止您執行以下操作:
(new Category).id = 5;
但它可以讓你輕松做到:
const category = Object.assign(new Category, { id: 5 });
通過構造函數傳遞對象:
export class Category {
private _a: number;
private _b: string;
constructor(values: { a: number; b: string }){
this._a = values.a;
this._b = values.b;
}
public getA() { return this._a; }
public getB() { return this._b; }
}
你仍然可以使用或不使用JSON調用它:
let cat1 = Category (values: { a: 42, b: 'hello' });
let json = '{"a":42,"b":"hello"}'
let cat2 = Category (values: JSON.parse (json));
或者,將值保留在對象中而不是直接成員中。 這使得不必將對象映射到成員變量:
export class Category {
private _values: {
a: number;
b: string;
}
constructor(values: { a: number; b: string }){
this._values = values;
}
public getA() { return this._values.a; }
public getB() { return this._values.b; }
}
如果你想保留舊的構造函數,你可以這樣做:
export class Category {
private _values: {
a: number;
b: string;
}
constructor(a: number, b: string) {
this._values = { a: a, b: b };
}
public static make (values: { a: number; b: string }) {
this._values = values;
}
public getA() { return this._values.a; }
public getB() { return this._values.b; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.