javascript - 在 JavaScript 中将 JSON 字符串解析为特定的对象原型(pr

我知道如何解析 JSON 字符串并将其转换为 JavaScript 对象。 您可以在现代浏览器(和 IE9+)中使用 JSON.parse()

这很好,但是我怎样才能把那个 JavaScript 对象变成一个 特定的 JavaScript 对象(即具有特定原型(prototype))?

例如,假设您有:

function Foo()
{
   this.a = 3;
   this.b = 2;
   this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse({"a":4, "b": 3});
//Something to convert fooJSON into a Foo Object
//....... (this is what I am missing)
alert(fooJSON.test() ); //Prints 12

同样,我不知道如何将 JSON 字符串转换为通用 JavaScript 对象。我想知道如何将 JSON 字符串转换为“Foo”对象。也就是说,我的对象现在应该有一个函数“test”和属性“a”和“b”。

更新 经过一番研究,我想到了这个……

Object.cast = function cast(rawObj, constructor)
{
    var obj = new constructor();
    for(var i in rawObj)
        obj[i] = rawObj[i];
    return obj;
}
var fooJSON = Object.cast({"a":4, "b": 3}, Foo);

这行得通吗?

2017 年 5 月更新:执行此操作的“现代”方式是通过 Object.assign ,但此功能在 IE 11 或更早的 Android 浏览器中不可用。

最佳答案

当前答案包含大量手卷或库代码。这不是必需的。

  1. 使用 JSON.parse('{"a":1}') 创建一个普通对象。

  2. 使用其中一种标准化函数来设置原型(prototype):

    • Object.assign(new Foo, { a: 1 })
    • Object.setPrototypeOf({ a: 1 }, Foo.prototype)

关于javascript - 在 JavaScript 中将 JSON 字符串解析为特定的对象原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5873624/

相关文章:

php - json_encode() 转义正斜杠

jquery - TypeError : $. ajax(...) 不是函数?

ios - 如何使用 NSJSONSerialization

python - Python有三元条件运算符吗?

javascript - 将对象字符串转换为 JSON

python - 存储 Python 字典

python - 如何在 Python 中检查字符串是否是有效的 JSON?

python - 将类实例序列化为 JSON

python - 如何将网页中的 JSON 转换为 Python 脚本

ios - 如何将 JSON 字符串反序列化为 NSDictionary? (适用于 iOS 5+)