213 votes

Analyser la chaîne JSON dans un prototype d'objet particulier en JavaScript

Je sais comment analyser une Chaîne JSON et le transformer en un Objet JavaScript. Vous pouvez utiliser la fonction eval() de jQuery.parseJSON().

C'est très bien, mais comment puis-je prendre cet Objet JavaScript et le transformer en un particulier d'Objet JavaScript (c'est à dire avec un certain prototype)?

Par exemple, supposons que vous avez:

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 = jQuery.parseJSON({"a":4, "b": 3});
//Something to convert fooJSON into a Foo Object
//....... (this is what I am missing)
alert(fooJSON.test() ); //Prints 12

Encore une fois, je ne suis pas demandez comment convertir une chaîne JSON dans un générique d'Objet JavaScript. Je veux savoir comment faire pour convertir une chaîne JSON dans un "Foo" de l'Objet. C'est, à mon Objet devriez maintenant avoir une fonction "test" et les propriétés de 'a' et 'b'.

Mise à JOUR Après avoir fait quelques recherches, j'ai pensé à cela...

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

Ce travail?

81voto

Oliver Moran Points 1924

Voir un exemple ci-dessous (cet exemple utilise l'objet JSON natif). Mes modifications sont commentées en majuscules:

 function Foo(obj) // CONSTRUCTOR CAN BE OVERLOADED WITH AN OBJECT
{
    this.a = 3;
    this.b = 2;
    this.test = function() {return this.a*this.b;};

    // IF AN OBJECT WAS PASSED THEN INITIALISE PROPERTIES FROM THAT OBJECT
    for (var prop in obj) this[prop] = obj[prop];
}

var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6

// INITIALISE A NEW FOO AND PASS THE PARSED JSON OBJECT TO IT
var fooJSON = new Foo(JSON.parse('{"a":4,"b":3}'));

alert(fooJSON.test() ); //Prints 12
 

46voto

Gabriel Llamas Points 5808

Voulez-vous ajouter JSON de sérialisation/désérialisation de fonctionnalités, non? Alors regardez ceci:

Vous souhaitez réaliser ceci:

UML

la méthode toJson() est une méthode normale.
fromJson() est une méthode statique.

Mise en œuvre:

var Book = function (title, author, isbn, price, stock){
    this.title = title;
    this.author = author;
    this.isbn = isbn;
    this.price = price;
    this.stock = stock;

    this.toJson = function (){
        return ("{" +
            "\"title\":\"" + this.title + "\"," +
            "\"author\":\"" + this.author + "\"," +
            "\"isbn\":\"" + this.isbn + "\"," +
            "\"price\":" + this.price + "," +
            "\"stock\":" + this.stock +
        "}");
    };
};

Book.fromJson = function (json){
    var obj = JSON.parse (json);
    return new Book (obj.title, obj.author, obj.isbn, obj.price, obj.stock);
};

Utilisation:

var book = new Book ("t", "a", "i", 10, 10);
var json = book.toJson ();
alert (json); //prints: {"title":"t","author":"a","isbn":"i","price":10,"stock":10}

var book = Book.fromJson (json);
alert (book.title); //prints: t

Remarque: Si vous le souhaitez, vous pouvez modifier tous les biens comme des définitions this.title, this.author,, etc en var title, var author, etc. et d'ajouter que les accesseurs à la réalisation de l'UML définition.

20voto

BMiner Points 4471

Un article de blog que j'ai trouvé utile: comprendre les prototypes JavaScript

Vous pouvez jouer avec la propriété __proto__ de l'objet.

 var fooJSON = jQuery.parseJSON({"a":4, "b": 3});
fooJSON.__proto__ = Foo.prototype;
 

Cela permet à fooJSON d'hériter du prototype Foo.

Je ne pense pas que cela fonctionne dans IE, cependant ... du moins d'après ce que j'ai lu.

2voto

BMiner Points 4471

J'ai aimé ton idée, Oliver. Que dis-tu de ça?

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

-1voto

 Object.cast = function(rawObj, constructor)
{
    var obj = new constructor();
    for (var i in rawObj) {
        eval("obj." + i + "=rawObj." + i);
    }
    return obj;
};

var fooJSON = Object.cast(jQuery.parseJSON({"a":4, "b": 3}), Foo);
 

Cela fonctionnera.

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X