将JSON反序列化为JAVASCRIPT对象 [英] deserialize JSON to JAVASCRIPT object

查看:118
本文介绍了将JSON反序列化为JAVASCRIPT对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有这个JSON:

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

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

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

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

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

不起作用,var obj和obj2不是标识符对象,我该如何解析呢? 谢谢

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

这个问题不是重复的,因为它比迈克尔标记为重复的问题早了5年

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

推荐答案

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

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

这篇关于将JSON反序列化为JAVASCRIPT对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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