我有一个我希望能够保存的对象模型。我将把它导出为 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/