Kalamarico Kalamarico - 27 days ago 5
Javascript Question

deserialize JSON to JAVASCRIPT object

i have a question to deserialize JSON text to an javascript object, i test jquery and yui library, i have this class:

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;
}


and i have this JSON:

{
"Identifier": {
"name":"uno",
"contextId":"dos"}
}


I want to the parse create an Identifier object, my problem is that this sentences:

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


or

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


Dont work, the var obj and obj2 aren't an Identifier object, how can i parse this?
Thanks

Answer

You could create a function that initializes those objects for you. Here's one I quickly drafted:

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;
}

This creates an object of the type represented by the name of the first attribute, and assigns it's values according to the attributes of the object of the first attribute. You could use it like that:

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

Live example