如何在Angular 7中的Json序列化中添加类型信息
大家好,为了得到这个结果,我需要在Angular 7中的Json序列化中添加类型信息(添加行"$type":"Person",):
{
"$type": "Person",
"id": 8,
"firstName": "Anke",
"lastName": "Winkler",
…
}我需要它,以便使用Json.NET在C#中反序列化,并且知道在使用接口类型的属性可能是不同类型的情况下使用哪种类型。非常感谢你的建议!
发布于 2019-03-24 17:08:05
这不是一个角度序列化问题,而是一个TypeScript/JavaScript问题。
您可以通过重写TypeScript类中的toJSON()方法来自定义序列化。
class User {
public id: number;
public firstName: string;
public lastName: string;
public age: number;
public toJSON(): User {
return Object.assign({}, this, {
$type: 'User'
});
}
}toJSON()方法要做的只是使用当前对象创建一个新对象,并向其添加$type属性。它将在您调用JSON.stringify()方法时调用。因此,您不需要在类中创建$type变量。
示例:
const newUser: User = new User();
newUser.id = 8;
newUser.firstName = "John";
newUser.lastName = "Doe";
newUser.age = 42;
const newUserAsJson: string = JSON.stringify(newUser);
console.log(newUserAsJson);
// Displays:
// {firstName: "John", lastName: "Doe", id: 8, age: 42, $type: "User"}希望能有所帮助。
https://stackoverflow.com/questions/55322009
复制相似问题