将JSON反序列化为JAVASCRIPT对象

Kal*_*ico 8 javascript json

我有一个问题要将JSON文本反序列化为javascript对象,我测试jquery和yui库,我有这个类:

function Identifier(name, contextId) {
    this.name = name;
    this.contextId = contextId;
}

Identifier.prototype.setName = function(name) {
    this.name = name;
}

Identifier.prototype.getName = function() {
    return this.name;
}

Identifier.prototype.setContextId = function(contexId) {
    this.contextId= contexId;
}

Identifier.prototype.getContextId = function() {
    return this.contextId;
}
Run Code Online (Sandbox Code Playgroud)

我有这个JSON:

{
"Identifier": { 
   "name":"uno",
   "contextId":"dos"}
}
Run Code Online (Sandbox Code Playgroud)

我想在解析时创建一个Identifier对象,我的问题是这句话:

var obj = jQuery.parseJSON('{"Identifier": { "name":"uno","contextId":"dos"}}');
Run Code Online (Sandbox Code Playgroud)

要么

var obj2 = JSON.parse('{"Identifier": { "name":"uno","contextId":"dos"}}');
Run Code Online (Sandbox Code Playgroud)

不工作,var obj和obj2不是Identifier对象,我该怎么解析呢?谢谢

这个问题不是重复的,因为它是在迈克尔标记为重复的问题之前5年制作的

Ale*_*pin 8

您可以创建一个为您初始化这些对象的函数.这是我快速起草的一个:

function parseJSONToObject(str) {
    var json = JSON.parse(str);

    var name = null;
    for(var i in json) { //Get the first property to act as name
        name = i;
        break;
    }

    if (name == null)
        return null;

    var obj = new window[name]();
    for(var i in json[name])
        obj[i] = json[name][i];

    return obj;
}
Run Code Online (Sandbox Code Playgroud)

这将创建一个由第一个属性的名称表示的类型的对象,并根据第一个属性的对象的属性分配它的值.你可以像这样使用它:

var identifier = parseJSONToObject('{"Identifier": { "name":"uno","contextId":"dos"}}');
console.log(identifier);
Run Code Online (Sandbox Code Playgroud)

实例