JSON with classes? JSON with classes? json json

JSON with classes?


You'll have to create your own serializer which detects Question (and other classes) and serializes them as constructor calls instead of JSON object notation. Note that you'll need a way to map an object to a constructor call. (Which properties come from which parameters?)

Everyone else: By classes he means functions used as constructors; I assume that he's trying to preserve the prototype.


Have you looked at JSON.NET? It can serialize/de-serialize .NET objects to JS and vice-versa. It is a mature project and I highly recommend it.

Also, if you could change the definition of your 'Question' function to take one object with properties instead of taking separate arguments, you can do something like this:

Working Demo

 function Question(args) {  this.id = args.id;  this.text = args.text; } Question.prototype.alertText = function() { alert(this.text); }; $(document).ready(  function()  {   var objectList =      {      'list' : [        { 'id' : 1, 'text' : 'text one' }       ,{ 'id' : 2, 'text' : 'text two' }       ,{ 'id' : 3, 'text' : 'text three'}       ],      'type' : 'Question'     };   var functionName = objectList['type'];   var constructor = window[functionName];   if(typeof constructor !== 'function')   {    alert('Could not find a function named ' + functionName);    return;   }   var list = objectList['list'];   $.each(list,    function()    {     var question = new constructor(this);     question.alertText();    }   );  } );

On a side note, please prefix your .NET Interfaces with 'I' e.g. it should be IJsonType and not JsonType.

typeof is a keyword so specify the property name in quotes if you want to use it.


It's highly dangerous, but eval can process any text and execute it.http://www.w3schools.com/jsref/jsref_eval.asp

But DON'T use it. May do something like pass over the params you want to pass into the constructor as a JSON object and call the constructor with it...

function Question({"id" : "val", "title", "mytitle", "description" : "my desc"}){...}