我从远程REST服务器读取了一个JSON对象。这个JSON对象具有typescript类的所有属性(根据设计)。我如何转换收到的JSON对象的类型var?
我不想填充一个typescript变量(即有一个构造函数,以这个JSON对象)。它很大,在子对象和属性之间复制所有内容将花费大量时间。
更新:你可以将它转换为typescript接口!
我从远程REST服务器读取了一个JSON对象。这个JSON对象具有typescript类的所有属性(根据设计)。我如何转换收到的JSON对象的类型var?
我不想填充一个typescript变量(即有一个构造函数,以这个JSON对象)。它很大,在子对象和属性之间复制所有内容将花费大量时间。
更新:你可以将它转换为typescript接口!
当前回答
我认为json2typescript是一个不错的选择 https://www.npmjs.com/package/json2typescript
你可以用一个带有注释的简单模型类将json转换为Class模型
用于工程
其他回答
假设json具有与typescript类相同的属性,你不需要将json属性复制到typescript对象中。你只需要在构造函数中传递json数据来构造Typescript对象。
在你的ajax回调中,你会收到一个company:
onReceiveCompany( jsonCompany : any )
{
let newCompany = new Company( jsonCompany );
// call the methods on your newCompany object ...
}
为了使它起作用:
1)在Typescript类中添加一个构造函数,将json数据作为参数。在该构造函数中,使用jQuery扩展json对象,如下所示:extend(this, jsonData)。美元。扩展允许保留javascript原型,同时添加json对象的属性。
2)注意你必须对链接对象做同样的事情。在本例中的Employees中,还创建了一个构造函数,用于接收Employees的json数据部分。你调用$。将json雇员转换为typescript雇员对象。
export class Company
{
Employees : Employee[];
constructor( jsonData: any )
{
$.extend( this, jsonData);
if ( jsonData.Employees )
this.Employees = $.map( jsonData.Employees , (emp) => {
return new Employee ( emp ); });
}
}
export class Employee
{
name: string;
salary: number;
constructor( jsonData: any )
{
$.extend( this, jsonData);
}
}
这是我在处理Typescript类和json对象时发现的最佳解决方案。
我发现了一篇关于将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
使用从接口扩展的类。
然后:
Object.assign(
new ToWhat(),
what
)
和最好的:
Object.assign(
new ToWhat(),
<IDataInterface>what
)
ToWhat成为DataInterface的控制器
你可以用一个tapi.js! 这是一种轻便的自动装置,可以双向工作。
npm i -D tapi.js
然后你就可以简单地做了
let typedObject = new YourClass().fromJSON(jsonData)
或者用承诺
axios.get(...).as(YourClass).then(typedObject => { ... })
你可以在文档里读到更多。
这是一个简单而又非常好的选择
let person = "{"name":"Sam","Age":"30"}";
const jsonParse: ((key: string, value: any) => any) | undefined = undefined;
let objectConverted = JSON.parse(textValue, jsonParse);
然后你会得到
objectConverted.name