首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将JavaScript对象序列化为JSON返回"{}",但为什么?

将JavaScript对象序列化为JSON返回"{}",但为什么?
EN

Stack Overflow用户
提问于 2014-07-30 12:06:37
回答 1查看 106关注 0票数 0

你好,StackOverflowers,

我正在为我的web应用程序实现一个LocalStorage系统。

但我遗憾的是,模型抽象层中的所有对象都必须序列化。

我知道当对象被转换为JSON时,函数不会被序列化。

我正要使用Option 1 described here。(也就是说,创建一个“静态”方法来返回一个全新的对象,包括函数)。

然而,问题是,即使是对象的非函数成员也没有被转换。

例如,在divvie.textContent = JSON.stringify(咖啡);,divvie.textContent变成"{}“。

为什么?到底怎么回事?

示例代码,不是我真正的应用程序,但情况非常相同:检查咖啡。

代码语言:javascript
复制
                var coffee = new Coffee( "0001", "DE Red Coarse",
                    "Douwe Egberts, red & coarse grounded." );
                coffee.addSugarCube( "0x0F_BROWN", "15" );
                coffee.addSugarCube( "0x0C_WHITE", "12" );

                var divvie = document.getElementById( "run" );
                divvie.textContent = JSON.stringify( coffee );
        </script>
    </body>
</html>

/**
 * @class This class represents a coffee.
 *
 * @param {String} id
 * @param {String} name
 * @param {String} description
 * @returns {Coffee}
 */
function Coffee( id, name, description )
{
    var sugarCubes = new Array();

    var maxAmountOfSweetness = 0;

    /**
     * @returns {String}
     */
    this.getId = function()
    {
        return id;
    };

    /**
     * @returns {String}
     */
    this.getName = function()
    {
        return name;
    };

    /**
     * @returns {String}
     */
    this.getDescription = function()
    {
        return description;
    };

    /**
     * @param {String} sugarCubeId
     * @param {Number} amountOfSweetness
     */
    this.addSugarCube = function( sugarCubeId, amountOfSweetness )
    {
        /// First check if this sugarCube is already in our coffee.
        var sugarCubeFound = false;

        for( var i = 0; i < sugarCubes.length; i++ )
        {
            if( sugarCubes[ i ].getId() === sugarCubeId )
            {
                sugarCubeFound = true;

                i = sugarCubes.length;
            }
        }

        if( !sugarCubeFound )
        {
            /// Oh Sweet! A new sugar cube to add in our coffee!
            sugarCubes.push( new SugarCube( sugarCubeId, amountOfSweetness ) );
            maxAmountOfSweetness = Math.max( maxAmountOfSweetness, amountOfSweetness );
        }
    };

    /**
     * @param {String} sugarCubeId
     * @returns {SugarCube}
     */
    this.getSugarCube = function( sugarCubeId )
    {
        for( var i = 0; i < sugarCubes.length; i++ )
        {
            if( sugarCubes[ i ].getId() === sugarCubeId )
            {
                return sugarCubes[ i ];
            }
        }
    };

    /**
     * @returns {Boolean} True when the amount of sugar cubes in this coffee is 1 or more,
     * false when not.
     */
    this.isSweet = function()
    {
        if( 0 < sugarCubes.length )
        {
            return true;
        }
        return false;
    };
}

/**
 * @class This class represents a sugar cube
 *
 * @param {String} id
 * @param {Number} amountOfSweetness
 * @returns {SugarCube}
 */
function SugarCube( id, amountOfSweetness )
{
    /**
     * @returns {String}
     */
    this.getId = function()
    {
        return id;
    };

    /**
     * @returns {Number}
     */
    this.getAmountOfSweetness = function()
    {
        return amountOfSweetness;
    };
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-30 12:10:45

Coffee构造函数创建的实例上唯一的属性似乎是方法,它们没有JSON表示(因为它们是函数)。您的数据都保存为创建的闭包中的variable或参数。这些不是属性,因此也不是JSON设计的对象。

要使它像预期的那样工作,您需要编写自己的toJSON方法,或者将数据从var移到属性

例如,使用属性

代码语言:javascript
复制
function Coffee(id, name, description) {
    this.id = id;
    this.name = name;
    this.description = description;
    this.sugarCubes = [];
    this.maxAmountOfSweetness = 0;
}
// and now you could even move the methods into the prototype
Coffee.prototype = {
    getId: function () {return this.id;}
    // etc

};
// new Coffee() is now JSON-able

您可能使用var来“隐藏”数据,使其仅通过您的方法公开,因此,另一种方法是添加一个新方法,将其转换为JSON。

代码语言:javascript
复制
// in Coffee
this.toJSON = function (a, b) {
    var o = {
        id: id,
        name: name
        // etc
    };
    return JSON.stringify(o, a, b);
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25036418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档