javascript - Dojo:如何从 JSON 加载对象(包含其他对象)?

标签 javascript json serialization dojo deserialization

我有一个我希望能够保存的对象模型。我将把它导出为 JSON,然后以 JSON 形式读回。

保存为 JSON 很容易。只需使用这个:JSON.stringify(this)

从 JSON 加载并不那么简单。

  • 我们不能只使用 this = JSON.parse(someJson),因为不会附加这些方法。
  • 使用诸如 lang.mixin(this, JSON.parse(someJson)) 之类的东西将获得函数,但对象是

照片类别:

define([...], function(...){
    return declare(null, {
        name: ..., // String
        url:..., // String
        complexProperty:..., // Some other class

        someFunction1: function(...){..},
        someFunction2: function(...){..},
        someFunction2: function(...){..}
    }
));

相册类:

define([...], function(...){
    return declare(null, {
        photos: [], /* Array of type Photo (see above) */
        someOtherProperty: ...,
        someOtherProperty: ...,

        someFunction1: function(...){..},
        someFunction2: function(...){..},
        someFunction2: function(...){..},

        toJson: function(){
            return JSON.stringify(this);    // From dojo/json
        }

        loadFromJson: function(jsonIn){
            // How to do this?
        }, 

        /* This doesn't work because methods will be overridden */
        loadFromJson1: function(jsonIn){
            this = JSON.parse(someJson);
        }, 

        /* This insures that my methods are kept intact but my childrens methods arn't (ie: the array of photos) */
        loadFromJson2: function(jsonIn){
            lang.mixin(this, JSON.parse(someJson));
        }, 

        /* This seems like an aweful lot of work.  Any better ways to do this? */
        loadFromJson3: function(jsonIn){
            this.someOtherProperty = jsonIn.someOtherProperty;
            this.someOtherProperty = jsonIn.someOtherProperty;
            foreach(jsonIn.photos: photoJson){
                var newPhoto = new Photo();
                newPhoto.loadfromJson(photoJson);
                this.photos.add(newPhoto);
            }
            ... All other properties set recursively.  All things in model now need this method ...
        }
    }
));

最佳答案

我认为您最好返回一个 JSON 对象,该对象仅包含您需要序列化的数据,而不是整个类。那么您的 loadFromJson 方法会更容易实现一些,并且您不会通过网络发送不必要的数据。 toJson() 示例:

toJson: function() {
    return JSON.stringify({
        photos: this.photos,
        someImportantProp: this.someImportantProp,
        anotherProp: this.anotherProp
    });
}

关于javascript - Dojo:如何从 JSON 加载对象(包含其他对象)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22945894/

相关文章:

javascript - Scroll-Magic - 停止重播动画?

java - 逐行读取序列化文件中的内容

java - java中的OpenCV Mat对象序列化

javascript - 为什么 OnClick 不改回颜色?

JavaScript 运行时错误 : 'fidoCallback' is undefined

javascript - JS中的换行\n问题

javascript - 如何在 json 中创建以下内容并在 javascript 中作为数组获取并搜索特定值?

c# - 使用 [JsonProperty] 将 Json 参数与类型为 List 的 C# 类属性匹配

java - 使用ajax请求发送时json值返回null

java - 任务在 Spark 中不可序列化