deserialize JSON to JAVASCRIPT object [duplicate]

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

This question is not the duplicate, because it was made 5 years before than the question that Michael marks as duplicated

Answers:

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.