I have this class:
export class TblColabAdmin {
snomatrcompl: string;
nflativo: number;
ativo: boolean;
}
The attribute ativo doesn't exist in my web service entity, so I would like to avoid that it was added in JSON.
In Java, for example, we have @JsonIgnore annotation. Does exist something similar in TypeScript?
The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
TS has a JavaScript runtime Typescript has a JavaScript runtime because it gets compiled to JS. This means JS objects which are built in as part of the language such as JSON , Object , and Math are also available in TS. Therefore we can just use the JSON. parse method to parse the JSON string.
1) Add a constructor in your Typescript class that takes the json data as parameter. In that constructor you extend your json object with jQuery, like this: $. extend( this, jsonData) .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With