How do I initialize a TypeScript object with a JSON object

前端 未结 16 852
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 08:30

I receive a JSON object from an AJAX call to a REST server. This object has property names that match my TypeScript class (this is a follow-on to this question).

Wha

16条回答
  •  迷失自我
    2020-11-22 09:15

    I've been using this guy to do the job: https://github.com/weichx/cerialize

    It's very simple yet powerful. It supports:

    • Serialization & deserialization of a whole tree of objects.
    • Persistent & transient properties on the same object.
    • Hooks to customize the (de)serialization logic.
    • It can (de)serialize into an existing instance (great for Angular) or generate new instances.
    • etc.

    Example:

    class Tree {
      @deserialize public species : string; 
      @deserializeAs(Leaf) public leafs : Array;  //arrays do not need extra specifications, just a type.
      @deserializeAs(Bark, 'barkType') public bark : Bark;  //using custom type and custom key name
      @deserializeIndexable(Leaf) public leafMap : {[idx : string] : Leaf}; //use an object as a map
    }
    
    class Leaf {
      @deserialize public color : string;
      @deserialize public blooming : boolean;
      @deserializeAs(Date) public bloomedAt : Date;
    }
    
    class Bark {
      @deserialize roughness : number;
    }
    
    var json = {
      species: 'Oak',
      barkType: { roughness: 1 },
      leafs: [ {color: 'red', blooming: false, bloomedAt: 'Mon Dec 07 2015 11:48:20 GMT-0500 (EST)' } ],
      leafMap: { type1: { some leaf data }, type2: { some leaf data } }
    }
    var tree: Tree = Deserialize(json, Tree);
    

提交回复
热议问题