gpt4 book ai didi

json - 如何在 Angular 7 的 Json 序列化中添加类型信息

转载 作者:行者123 更新时间:2023-12-01 21:58:02 25 4
gpt4 key购买 nike

如何在Angular 7中的Json序列化中添加类型信息

大家好,为了得到这个结果,我需要在 Angular 7 的 Json 序列化中添加类型信息(添加行“$type”:“Person”,):

{
"$type": "Person",
"id": 8,
"firstName": "Anke",
"lastName": "Winkler",

}

我需要这个以便在 C# 中使用 Json.NET 进行反序列化,并知道在使用接口(interface)键入的属性的情况下使用哪种类型,因此可能属于不同类型。非常感谢任何建议!

最佳答案

这不是 Angular 序列化问题,而是 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"}

希望对您有所帮助。

关于json - 如何在 Angular 7 的 Json 序列化中添加类型信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55322009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com