【问题标题】:Casting JSON to TS Object将 JSON 转换为 TS 对象
【发布时间】:2019-01-26 17:09:05
【问题描述】:

我有一些这样的json;

example.json

{
    "id": 1,
    "name": "John Doe",
    "age": 23,
    "country": "US",
    "language": "en",
    "created_at": 1534774253,
    "updated_at": 1534774269
}

我有一个这样的 user.ts 界面;

user.ts

interface user {
    id: number;
    name: string;
    age: number;
    country: string
}

那么,我怎样才能把这个 json 转换成一个从这个接口实现的对象呢?我尝试了const userObj: user = JSON.parse(exampleJson);,但 userObj 具有 json 中的所有属性。我想生成一个只有 user.ts 属性的用户对象。 例如=>JSON.stringify(userObj);,输出为{"id":1,"name":"John Doe","age":23,"country":"US"}。

有人知道方法吗?

【问题讨论】:

  • 这在我看来不像是重复的:问题是关于删除 TypeScript 界面中不存在的属性。
  • 这个 JSON 是从哪里来的? TS 类型导入的 JSON 文件。
  • @estus 它通过 REST 来自远程服务器。
  • @MattMcCutchen 来自公认的答案:“你不能简单地将一个普通的旧 JavaScript 结果......转换为原型 JavaScript/TypeScript 类实例。” + "...,您可以只对接口进行强制转换(因为它纯粹是一个编译时结构)" -> 解析 JSON,去除无用的属性,强制转换为 user(应该被命名为IUser,恕我直言)

标签: json node.js typescript


【解决方案1】:

Typescript 接口是一种帮助向您的代码编辑器提供 intellisense(提示)和强类型化 JSON 的方法。它没有帮助您清除不需要的其他属性的功能。因此,当您执行const userObj: user = JSON.parse(exampleJson) 时,您仍然会得到类似created_at 的属性。

我认为您可以实现所需的一种方法可能是编写一个类。

class User {
  id: number;
  name: string;
  age: number;
  country: string;

  constructor(jsonString: any) {
    const userObj = JSON.parse(jsonString);

    // this part could be shorten with for loop
    this.id = userObj.id;
    this.name = userObj.name;
    this.age = userObj.age;
    this.country = userObj.country;
  }
}

以后就可以使用了:

const userObj = new User(exampleJson);

【讨论】:

  • 感谢您的回答。这似乎是正确的做法,但我想问一些事情。如果我的 json 有很多用户对象,我应该为所有这些对象创建新的用户对象吗?
  • 在这种情况下,我假设你的 json 是一个数组。您可以为所有这些创建一个用户对象。没关系。只有一行这很简单:const userList = (JSON.parse(exampleJson)).map(x => new User(x));
  • 另一种处理此问题的方法是 - 如果您知道要选择或省略的属性列表,您可以使用 lodash pick 或 omit 之类的东西来选择或省略其他属性,然后再分配给你的userObj。
【解决方案2】:

您创建一个函数,或者最好是一个名为“valueObjects”的文件,它接受传入的对象,然后返回所需的对象。这是我拥有的一些代码的示例:

export const Address = ({
	Street = null,
	Street2 = null,
	City = null,
	State = null,
	ZipCode = null,
	Country = 'US',
	IsVerified = null,
	IsActive = true,
	StudentID = null,
	Description = null,
	IsPrimary = null,
	AddressID = null,
	DateCreated = null,
	DateUpdated = null
} = {}) => ({
	Street,
	Street2,
	City,
	State,
	ZipCode,
	Country,
	IsVerified,
	IsActive,
	StudentID,
	Description,
	IsPrimary,
	AddressID,
	DateCreated,
	DateUpdated
});

那么你需要做的就是Address(yourObj)

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 1970-01-01
    • 2014-10-10
    • 2017-06-16
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多