Unmarshalling Dojo fromJson() with declaredClass

May 11th, 2011

If you’ve ever tried to unmarshall a Dojo object using the fromJson() method, you were probably annoyed to discover that none of your object’s methods were available to you. This is because the Dojo fromJson() method merely deserializes what you have, ignoring any links to theĀ declaredClass property. Here’s a little code that will do the work of classloading and giving you access to all your properties and methods:

 

		function deserializeJsonString(s)
		{
			return deserializeJson(eval('('+s+')'));
		}

		function deserializeJson(obj)
		{

			if( obj.declaredClass ){

				var o= null;

				try{
					o= eval('new '+ obj.declaredClass+'()');
				} catch (e){
					console.warn('Did not find the class:'+ obj.declaredClass+ ' ... loading...')
					dojo.require(obj.declaredClass);
					o= eval('new '+ obj.declaredClass+'()');
				} 

				for(var i in obj)
				{
					if(typeof o[i]  =='undefined')
					{
						console.warn(' property "'+ i+ '" does not exist in '+ o.declaredClass+ ' for object with id '+ o.id)
					}

					var prop= obj[i];

					if(prop!= null){
						if(prop instanceof Array)
						{
							var a= [];
							for(var j= 0; j< prop.length; j++){
								a[j]= deserializeJson(prop[j]);
							}

							o[i]= a;

						} else if(prop.declaredClass) {

							var childClass= deserializeJson(prop);
							o[i]= childClass;

						} else {
							o[i]= prop;
						}
					}
				}

				return o ;

			} else if(obj instanceof Array){

				var oa= [];

				for(var i= 0; i< obj.length; i++){
					oa.push(deserializeJson(obj[i]));
				}

				return oa;

			} else {
				return obj;
			}

		}

 

 


Leave a Reply