Best way to serialize/unserialize objects in JavaScript?

前端 未结 8 1409
忘掉有多难
忘掉有多难 2020-11-27 13:53

I have many JavaScript objects in my application, something like:

function Person(age) {
    this.age = age;
    this.isOld = function (){
        return thi         


        
8条回答
  •  独厮守ぢ
    2020-11-27 13:59

    I am the author of https://github.com/joonhocho/seri.

    Seri is JSON + custom (nested) class support.

    You simply need to provide toJSON and fromJSON to serialize and deserialize any class instances.

    Here's an example with nested class objects:

    import seri from 'seri';
    
    class Item {
      static fromJSON = (name) => new Item(name)
    
      constructor(name) {
        this.name = name;
      }
    
      toJSON() {
        return this.name;
      }
    }
    
    class Bag {
      static fromJSON = (itemsJson) => new Bag(seri.parse(itemsJson))
    
      constructor(items) {
        this.items = items;
      }
    
      toJSON() {
        return seri.stringify(this.items);
      }
    }
    
    // register classes
    seri.addClass(Item);
    seri.addClass(Bag);
    
    
    const bag = new Bag([
      new Item('apple'),
      new Item('orange'),
    ]);
    
    
    const bagClone = seri.parse(seri.stringify(bag));
    
    
    // validate
    bagClone instanceof Bag;
    
    bagClone.items[0] instanceof Item;
    bagClone.items[0].name === 'apple';
    
    bagClone.items[1] instanceof Item;
    bagClone.items[1].name === 'orange';
    

    Hope it helps address your problem.

提交回复
热议问题