Javascript 将JSON解析为对象数组

Javascript 将JSON解析为对象数组,javascript,json,Javascript,Json,我在将JSON解析为对象数组时遇到问题 我有三个JavaScript类 宠物 猫延伸宠物 宠物狗 我想创建一个Pet对象数组,然后将其作为JSON存储在浏览器本地存储中 问题: function Pet(imageUrl, name, soundUrl) { this.imageUrl = imageUrl; this.name = name; this.soundUrl = soundUrl; this.talk = function() { }; }

我在将JSON解析为对象数组时遇到问题

我有三个JavaScript类

  • 宠物
  • 猫延伸宠物
  • 宠物狗
  • 我想创建一个Pet对象数组,然后将其作为JSON存储在浏览器本地存储中

    问题:

    function Pet(imageUrl, name, soundUrl) {
        this.imageUrl = imageUrl;
        this.name = name;
        this.soundUrl = soundUrl;
        this.talk = function() {
        };
    }
    function Cat(imageUrl, name, soundUrl, favoriteFood) {
        Pet.apply(this,arguments);
        this.favoriteFood=favoriteFood;
    }
    Cat.prototype=new Pet();
    Cat.prototype.constructor = Cat;
    function Dog(imageUrl, name, soundUrl, walkingTime) {
        Pet.apply(this,arguments);
        this.walkingTime=walkingTime;
    }
    Dog.prototype=new Pet();
    Dog.prototype.constructor = Dog;
    
    当我检索JSON并将其解析为object数组时,元素的原型从Cat或Dog变为object,所以当我测试

    pets[0] instanceof Cat // always false
    pets[0] instanceof Dog // always false
    
    有没有办法将元素的原型保持为原始对象而不是对象

    课程:

    function Pet(imageUrl, name, soundUrl) {
        this.imageUrl = imageUrl;
        this.name = name;
        this.soundUrl = soundUrl;
        this.talk = function() {
        };
    }
    function Cat(imageUrl, name, soundUrl, favoriteFood) {
        Pet.apply(this,arguments);
        this.favoriteFood=favoriteFood;
    }
    Cat.prototype=new Pet();
    Cat.prototype.constructor = Cat;
    function Dog(imageUrl, name, soundUrl, walkingTime) {
        Pet.apply(this,arguments);
        this.walkingTime=walkingTime;
    }
    Dog.prototype=new Pet();
    Dog.prototype.constructor = Dog;
    
    创建阵列后,我必须将其保存到浏览器本地存储

    var pets=[];
    var cat = new Cat('imageUrl','name','soundUrl','favoriteFood');
    pets.push(cat);
    localStorage.setItem('pets', JSON.stringify(pets));
    
    要检索阵列,请执行以下操作:

            if (localStorage.getItem('pets') !== null)
        {
         var pets = JSON.parse(localStorage.getItem('pets'));
        }
    

    是的,在JSON中只有普通的对象(和数组)。我能看到的解决这个问题的唯一方法是添加一个提供类的额外属性,然后在解析JSON之后,需要将结果对象转换为动物(以某种方式赋予它们生命)。

    一个@MauricePerry答案的实现示例:

    您希望向您的宠物类添加一个stringify方法,该方法返回一个普通对象,您可以稍后从中实例化动物对象

    例如:

    // add stringify function to your Pet class
    function Pet(imageUrl, name, soundUrl) {
        ...
        this.stringify = function () {
            var jsonRepresentation = {};
            for (attr in this) {
                if (typeof this[attr] != "function") {
                    jsonRepresentation[attr] = this[attr];
                }
            }
            return jsonRepresentation;
        };
    };
    
    // add a class property to your various pet subclasses
    // e.g. Cat.prototype.class = "cat";
    
    // create an instance of Cat
    var cat = new Cat('imageUrl','name','soundUrl','favoriteFood');
    
    // get the info to restore the cat instance later on
    var animalInfo = cat.stringify();
    
    /*
    cat info would be like:
    {
        "class": "cat",
        "imageUrl": "theUrl",
        "name": "theName",
        "soundUrl": "theSoundUrl",
        "favoriteFood": "theFavoriteFood"
    }
     */
    
    // then you would store the info to localStorage
    ...
    // later you could retrieve you cat instance like so
    var restoredAnimal;
    switch(animalInfo.class) {
        case "cat":
            restoredAnimal = new Cat(animalInfo.imageUrl, animalInfo.name, animalInfo.soundUrl, animalInfo.favouriteFood)
            break;
        default:
            console.log('there is no such animal');
    }
    

    不,因为要把整个代码,pets放在另一个名为HomePage function HomePage(){this.pets=[];}的类中需要很长时间。你有什么建议来找到普通对象属于哪个类,这样我才能构造正确的对象吗?正如我在帖子中所说的,我会添加一个属性,比如className,对于Cat,“Dog”,它将是“Cat”对于狗,等等…很抱歉,我没有看到它,我将使用这种方法看起来很简单而且很好。这种技术与@MauricePerry的回答很吻合。@erik.eistee从哪里获得animalInfo.class,因为我没有看到名为class的属性,它是从对象继承的还是应该添加它?如果我必须添加它,为什么我不能使用JSON.stringify()??@mohdalomary你想给你的动物子类添加一个class属性,这样你以后就可以区分实例化哪个子类了。您可以使用JSON.stringify,但您可以使用自己的stringify方法来控制您移交的属性(从某种意义上说,可能有一些私有属性)。