将JSON发送到Web服务时,如何忽略TypeScript中的实体字段? [英] How to ignore an entity field in TypeScript when sending a JSON to a Web Service?

查看:81
本文介绍了将JSON发送到Web服务时,如何忽略TypeScript中的实体字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上了这堂课:

export class TblColabAdmin {
    snomatrcompl: string;
    nflativo: number;
    ativo: boolean;
}

属性 ativo 在我的Web服务实体中不存在,因此,我想避免将其添加到JSON中.

The attribute ativo doesn't exist in my web service entity, so I would like to avoid that it was added in JSON.

例如,在Java中,我们有 @JsonIgnore 批注.在TypeScript中是否存在类似的东西?

In Java, for example, we have @JsonIgnore annotation. Does exist something similar in TypeScript?

推荐答案

您可以创建JsonIgnore

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}

(仅执行一次就需要大量工作,但是如果这是代码中的常见问题,那么这种方法应该可以很好地工作.

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.

这篇关于将JSON发送到Web服务时,如何忽略TypeScript中的实体字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆