You can create a JsonIgnore decorator to make it work like 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);
( code on the playground )
This is quite a lot of work if you do it only once, but if this is a common problem in your code, then this approach should work well.
source share