class User {
userid: number;
username: string;
age: number;
private password: string; // should not be serialized
constructor(userid: number, username: string, age: number, password: string) {
this.userid = userid;
this.username = username;
this.age = age;
this.password = password;
}
toJSON() {
// Exclude sensitive data like password
return {
userid: this.userid,
username: this.username,
age: this.age,
};
}
}
const user: User = new User(9382732, "A AI", 52, "ah@746Eo87R!");
// Convert class instance to JSON
const jsonString: string = JSON.stringify(user);
console.log("JSON String:", jsonString);
/*
run:
"JSON String:", "{"userid":9382732,"username":"A AI","age":52}"
*/