如何从JSON恢复原始对象/类型? [英] How to restore original object/type from JSON?

查看:193
本文介绍了如何从JSON恢复原始对象/类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用eval或JSON.parse,可以很容易地将JSON加载到javascript对象中.

Its easy to load JSON into an object in javascript using eval or JSON.parse.

但是,如果您具有适当的类"函数,如何将JSON数据放入其中?

But if you have a proper "class" like function, how do you get the JSON data into it?

例如

function Person(name) {
  this.name=name;
  this.address = new Array();
  this.friendList;

  this.promote = function(){
     // do some complex stuff
  }
  this.addAddress = function(address) {
    this.address.push(address)
  }
}

var aPersonJSON = '{\"name\":\"Bob\",\"address\":[{\"street\":\"good st\",\"postcode\":\"ADSF\"}]}'

var aPerson = eval( "(" + aPersonJSON + ")" ); // or JSON.parse
//alert (aPerson.name);    // Bob
var someAddress = {street:"bad st",postcode:"HELL"};
//alert (someAddress.street); // bad st
aPerson.addAddress(someAddress); // fail!

问题的关键是我需要能够从JSON创建适当的Person实例,但是我所能获得的只是一个愚蠢的对象.我想知道是否可以对原型做些什么?

The crux is I need to be able to create proper Person instances from JSON, but all I can get is a dumb object. Im wondering if its possible to do something with prototypes?

我不想解析JSON的每一行并将每个变量分配给coresponding函数属性,这太困难了.实际上,我拥有的JSON和函数比上面的示例复杂得多.

I dont want to have to parse each line of the JSON and assign each variable to the coresponding functions attributes, which would be too difficult. The actualy JSON and functions I have are much more complicated than the example above.

我假设可以将函数方法JSON化为JSON字符串,但是由于我需要将结果数据保持尽可能小,因此这不是一种选择-我只想存储和加载数据,而不是javascript代码方法.

I am assuming one could JSONify the functions methods into the JSON string, but as I need to keep the resultant data as small as possible this is not an option - I only want to store and load the data, not the javascript code for the methods.

如果我能帮忙的话,我也不想将JSON加载的数据作为子对象放置(但可能是唯一的方法),例如

I also dont want to have to put the data loaded by JSON as a sub object if I can help it (but might be the only way), e.g.

function Person(name) {
  this.data = {};
  this.data.name=name;
}

var newPerson = new Person("");
newPerson.data = eval( "(" + aPersonJSON + ")" );
alert (newPerson.data.name); // Bob

有什么想法吗?

推荐答案

您需要使用reviver函数:

// Registry of types
var Types = {};

function MyClass(foo, bar) {
  this._foo = foo;
  this._bar = bar;
}
Types.MyClass = MyClass;

MyClass.prototype.getFoo = function() {
  return this._foo;
}

// Method which will provide a JSON.stringifiable object
MyClass.prototype.toJSON = function() {
  return {
    __type: 'MyClass',
    foo: this._foo,
    bar: this._bar
  };
};

// Method that can deserialize JSON into an instance
MyClass.revive = function(data) {
  // TODO: do basic validation
  return new MyClass(data.foo, data.bar);
};

var instance = new MyClass('blah', 'blah');

// JSON obtained by stringifying an instance
var json = JSON.stringify(instance); // "{"__type":"MyClass","foo":"blah","bar":"blah"}";

var obj = JSON.parse(json, function(key, value) {
  return key === '' && value.hasOwnProperty('__type')
    ? Types[value.__type].revive(value)
    : this[key];
});

obj.getFoo(); // blah

别无他法...

这篇关于如何从JSON恢复原始对象/类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆