如何将JSON对象转换为Typescript类

本文翻译自:How do I cast a JSON object to a typescript class

I read a JSON object from a remote REST server. 我从远程REST服务器读取了JSON对象。 This JSON object has all the properties of a typescript class (by design). 此JSON对象具有Typescript类的所有属性(通过设计)。 How do I cast that received JSON object to a type var? 如何将收到的JSON对象转换为var类型?

I don't want to populate a typescript var (ie have a constructor that takes this JSON object). 我不想填充一个打字稿变量(即有一个采用此JSON对象的构造函数)。 It's large and copying everything across sub-object by sub-object & property by property would take a lot of time. 它很大,因此要在子对象之间按子对象复制所有内容,并按属性复制所有内容将花费大量时间。

Update: You can however cast it to a typescript interface! 更新:但是,您可以将其转换为打字稿界面!


#1楼

参考:https://stackoom.com/question/1Xyzs/如何将JSON对象转换为Typescript类


#2楼

You can't simple cast a plain-old-JavaScript result from an Ajax request into a prototypical JavaScript/TypeScript class instance. 您不能简单地将Ajax请求中的原始JavaScript结果转换为原型JavaScript / TypeScript类实例。 There are a number of techniques for doing it, and generally involve copying data. 有许多技术可以做到这一点,并且通常涉及复制数据。 Unless you create an instance of the class, it won't have any methods or properties. 除非您创建该类的实例,否则它将没有任何方法或属性。 It will remain a simple JavaScript object. 它将仍然是一个简单的JavaScript对象。

While if you only were dealing with data, you could just do a cast to an interface (as it's purely a compile time structure), this would require that you use a TypeScript class which uses the data instance and performs operations with that data. 如果仅处理数据,则可以强制转换为接口(因为它纯粹是编译时结构),这将要求您使用TypeScript类,该类使用数据实例并对该数据执行操作。

Some examples of copying the data: 复制数据的一些示例:

  1. Copying AJAX JSON object into existing Object 将AJAX JSON对象复制到现有对象
  2. Parse JSON String into a Particular Object Prototype in JavaScript 将JSON字符串解析为JavaScript中的特定对象原型

In essence, you'd just : 本质上,您只是:

var d = new MyRichObject();
d.copyInto(jsonResult);

#3楼

In TypeScript you can do a type assertion using an interface and generics like so: 在TypeScript中,您可以使用接口和泛型来进行类型断言 ,如下所示:

var json = Utilities.JSONLoader.loadFromFile("../docs/location_map.json");
var locations: Array = JSON.parse(json).location;

Where ILocationMap describes the shape of your data. ILocationMap在哪里描述数据的形状。 The advantage of this method is that your JSON could contain more properties but the shape satisfies the conditions of the interface. 此方法的优点是您的JSON可以包含更多属性,但形状可以满足接口的条件。

I hope that helps! 希望对您有所帮助!


#4楼

I found a very interesting article on generic casting of JSON to a Typescript Class: 我发现了一篇关于将JSON通用转换为Typescript类的非常有趣的文章:

http://cloudmark.github.io/Json-Mapping/ http://cloudmark.github.io/Json-Mapping/

You end up with following code: 您最终得到以下代码:

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

#5楼

I had the same issue and I have found a library that does the job : https://github.com/pleerock/class-transformer . 我遇到了同样的问题,并且找到了一个可以完成此工作的库: https : //github.com/pleerock/class-transformer 。

It works like this : 它是这样的:

        let jsonObject = response.json() as Object;
        let fooInstance = plainToClass(Models.Foo, jsonObject);
        return fooInstance;

It supports nested childs but you have to decorate your class's member. 它支持嵌套的子级,但是您必须装饰类的成员。


#6楼

While it is not casting per se; 虽然它本身不是演员; I have found https://github.com/JohnWhiteTB/TypedJSON to be a useful alternative. 我发现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"

你可能感兴趣的:(json,typescript)