Làm cách nào để tuần tự hóa các lớp này thành JSON?Kiểu chữ, sắp xếp lớp đối tượng
Như bạn có thể thấy từ ví dụ bên dưới JSON.stringify()
không tuần tự hóa danh sách Cache_Backend_LocalStorage_Tag
bên trong đối tượng Cache_Backend_LocalStorage_TagThree
.
Tôi đang thiếu gì?
interface Cache_Backend_LocalStorage_Tag_Interface {
_tag : string;
_keys : string[];
}
class Cache_Backend_LocalStorage_Tag implements Cache_Backend_LocalStorage_Tag_Interface {
public _tag : string;
public _keys : string[];
constructor(tag : string) {
this._tag = tag;
this._keys = [];
}
public add(key : string) : void {
this._keys.push(key);
}
public remove(key : string): boolean {
// Get the index of the key
var index = this._keys.indexOf(key, 0);
// Check if we found the keys index
if (index != undefined) {
this._keys.splice(index, 1);
return true;
}
return false;
}
public get tag(): string {
return this._tag;
}
public get keys(): string[] {
return this._keys;
}
}
interface Cache_Backend_LocalStorage_TagThree_Interface {
_tags : Cache_Backend_LocalStorage_Tag[];
}
class Cache_Backend_LocalStorage_TagThree implements Cache_Backend_LocalStorage_TagThree_Interface {
public _tags : Cache_Backend_LocalStorage_Tag[];
constructor(tags : Cache_Backend_LocalStorage_Tag[] = []) {
this._tags = tags;
}
public add(tag : Cache_Backend_LocalStorage_Tag) : void {
this.tags[tag.tag] = tag;
}
public get tags(): Cache_Backend_LocalStorage_Tag[] {
return this._tags;
}
public get(tagKey : string): Cache_Backend_LocalStorage_Tag {
return this.tags[tagKey];
}
public addKeyToTag(tagKey, key) {
this.tags[tagKey].add(key);
}
public removeKeyFromTag(tagKey, key) {
// Get the tag
var tag = this._tags[tagKey];
// Check if we found the tag index
if (tag != undefined) {
return tag.remove(key);
}
return false;
}
public clear(tagKey : string): void {
delete this._tags[tagKey];
}
public static fromObject(object): Cache_Backend_LocalStorage_TagThree {
return new Cache_Backend_LocalStorage_TagThree(object._tags);
}
}
Vấn đề:
var tagThree = new Cache_Backend_LocalStorage_TagThree();
tagThree.add(new Cache_Backend_LocalStorage_Tag("stores"));
tagThree.addKeyToTag("stores", "store5");
tagThree.removeKeyFromTag("stores", "store5");
// {"_tags":[]}
console.log(JSON.stringify(tagThree));
// { _tags: [ stores: { _tag: 'stores', _keys: [Object] } ] }
console.log(tagThree);
Cảm ơn câu trả lời kỹ lưỡng của bạn. – user634545
@ user634545 bằng cách này, bạn có thể muốn thay đổi nó để thay vào đó sử dụng một mảng. Nếu trường hợp đó xảy ra, bạn vẫn có thể có nó như là một mảng, chỉ cần chắc chắn rằng bạn lưu trữ chúng bằng một chỉ mục số (ví dụ: 'this._tags [0]') để tuần tự hóa thay vì là thuộc tính (ví dụ: 'this._tags [ "propertyName"] '). –
Thật tuyệt, tôi không biết về toJson. Cảm ơn – user634545