首页 > 解决方案 > 将 JSON 转换为 TS 对象

问题描述

我有一些这样的json;

例子.json

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

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

用户.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"}

有人知道方法吗?

标签: jsonnode.jstypescript

解决方案


Typescript 接口是一种帮助为您的代码编辑器提供智能感知(提示)和强类型化 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);

推荐阅读