You can create a JsonIgnore
decorator so that it will work like with java:
const IGNORE_FIELDS = new Map<string, string[]>();
function JsonIgnore(cls: any, name: string) {
let clsName = cls.constructor.name;
let list: string[];
if (IGNORE_FIELDS.has(clsName)) {
list = IGNORE_FIELDS.get(clsName);
} else {
list = [];
IGNORE_FIELDS.set(clsName, list);
}
list.push(name);
}
class Base {
toJson(): { [name: string]: any } {
let json = {};
let ignore = IGNORE_FIELDS.get(this.constructor.name);
Object.getOwnPropertyNames(this).filter(name => ignore.indexOf(name) < 0).forEach(name => {
json[name] = this[name];
});
return json;
}
}
class TblColabAdmin extends Base {
snomatrcompl: string;
nflativo: number;
@JsonIgnore
ativo: boolean;
constructor(snomatrcompl: string, nflativo: number, ativo: boolean) {
super();
this.snomatrcompl = snomatrcompl;
this.nflativo = nflativo;
this.ativo = ativo;
}
}
let obj = new TblColabAdmin("str", 43, true).toJson();
console.log(obj); // Object {snomatrcompl: "few", nflativo: 43}
(code in playground)
It's quite a lot of work if you're only doing it once, but if it's a common issue in your code then this approach should work well.