我有这堂课:
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
ativo 属性在我的网络服务实体中不存在,因此我想避免将其添加到JSON中。
例如,在Java中,我们有 @JsonIgnore 注释。在TypeScript中是否存在类似的东西?
答案 0 :(得分:6)
您可以创建JsonIgnore
decorator,以便它可以像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}
如果您只执行一次这项工作需要做很多工作,但如果这是您代码中的常见问题,那么此方法应该可以正常运行。
答案 1 :(得分:-1)
没有。最简单的方法是创建一个只包含要发送的属性的新对象。
例如:
this.http.post('someurl', {
snomatrcompl: data.snomatrcompl,
nflativo: data.nflativo
});