我从远程REST服务器读取了一个JSON对象。这个JSON对象具有typescript类的所有属性(根据设计)。我如何转换收到的JSON对象的类型var?
我不想填充一个typescript变量(即有一个构造函数,以这个JSON对象)。它很大,在子对象和属性之间复制所有内容将花费大量时间。
更新:你可以将它转换为typescript接口!
我从远程REST服务器读取了一个JSON对象。这个JSON对象具有typescript类的所有属性(根据设计)。我如何转换收到的JSON对象的类型var?
我不想填充一个typescript变量(即有一个构造函数,以这个JSON对象)。它很大,在子对象和属性之间复制所有内容将花费大量时间。
更新:你可以将它转换为typescript接口!
当前回答
我发现了一篇关于将JSON转换为Typescript类的非常有趣的文章:
http://cloudmark.github.io/Json-Mapping/
你最终会得到如下代码:
let example = {
"name": "Mark",
"surname": "Galea",
"age": 30,
"address": {
"first-line": "Some where",
"second-line": "Over Here",
"city": "In This City"
}
};
MapUtils.deserialize(Person, example); // custom class
其他回答
你可以使用这个npm包。https://www.npmjs.com/package/class-converter
它很容易使用,例如:
class UserModel {
@property('i')
id: number;
@property('n')
name: string;
}
const userRaw = {
i: 1234,
n: 'name',
};
// use toClass to convert plain object to class
const userModel = toClass(userRaw, UserModel);
// you will get a class, just like below one
// const userModel = {
// id: 1234,
// name: 'name',
// }
虽然它本身不是铸造;我发现https://github.com/JohnWhiteTB/TypedJSON是一个有用的替代方案。
@JsonObject
class Person {
@JsonMember
firstName: string;
@JsonMember
lastName: string;
public getFullname() {
return this.firstName + " " + this.lastName;
}
}
var person = TypedJSON.parse('{ "firstName": "John", "lastName": "Doe" }', Person);
person instanceof Person; // true
person.getFullname(); // "John Doe"
我在这里使用这个库:https://github.com/pleerock/class-transformer
<script lang="ts">
import { plainToClass } from 'class-transformer';
</script>
实现:
private async getClassTypeValue() {
const value = await plainToClass(ProductNewsItem, JSON.parse(response.data));
}
有时必须解析plainToClass的JSON值才能理解它是JSON格式的数据
我也遇到过类似的需求。 我想要一些能够让我轻松地从/转换到JSON的东西 这来自于对特定类定义的REST api调用。 我已经找到的解决方案是不够的,或者意味着重写我的 类的代码和添加注释或类似内容。
我想在Java中使用类似GSON的东西来序列化/反序列化类到JSON对象。
结合后来的需要,转换器也可以在JS中运行,我结束了编写自己的包。
它有一些开销。但启动后,添加和编辑非常方便。
初始化模块:
转换模式——允许在字段之间进行映射和确定 如何进行转换 类映射数组 转换函数映射-用于特殊转换。
然后在你的代码中,你像这样使用初始化的模块:
const convertedNewClassesArray : MyClass[] = this.converter.convert<MyClass>(jsonObjArray, 'MyClass');
const convertedNewClass : MyClass = this.converter.convertOneObject<MyClass>(jsonObj, 'MyClass');
或者,转换为JSON:
const jsonObject = this.converter.convertToJson(myClassInstance);
使用这个链接到npm包,以及如何使用模块:json-class-converter的详细说明
还包装了 Angular的用法: angular-json-class-converter
将对象原样传递给类构造函数;没有约定或检查
interface iPerson {
name: string;
age: number;
}
class Person {
constructor(private person: iPerson) { }
toString(): string {
return this.person.name + ' is ' + this.person.age;
}
}
// runs this as //
const object1 = { name: 'Watson1', age: 64 };
const object2 = { name: 'Watson2' }; // age is missing
const person1 = new Person(object1);
const person2 = new Person(object2 as iPerson); // now matches constructor
console.log(person1.toString()) // Watson1 is 64
console.log(person2.toString()) // Watson2 is undefined