Showing posts with label deserialize. Show all posts
Showing posts with label deserialize. Show all posts

Wednesday, March 21, 2012

trying to deserialize json to a C# class - do I use .Deserialize? .Deserialize<>?

Hello,

I have several classes that have been rendered to the client, each with their respective __Type properties. I have created a generic save() webmethod that I would like to invoke, passing any of the various serialized classes. But each attempt fails with various runtime errors. My original intent was:

[WebMethod]
public string save(object obj)
{
obj.save() // obj is casted to one of several c# classes depending upon the __Type property present
}

And I hoped/assumed that .NET Ajax would handle my deserializtion which it did not. My next attempt was to make the obj variable a string type and then try and deserialize manually inside the method. I have done this quite easily in the past with AjaxPro.

[WebMethod]
public string save(string obj)
{
System.Web.Script.Serialization.JavaScriptSerializer jser = new System.Web.Script.Serialization.JavaScriptSerializer()
myobj = (cs_class)jser.Deserialize<cs_class>(obj);

myobj.save();
obj.save() // obj is casted to one of several c# classes depending upon the __Type property present
}

I am now looking at System.Web.Script.Serialization.JavascriptSerializer.Deserialize<> and System.Web.Script.Serialization.JavascriptSerializer.DeserializeObject() but the documentation is sparse and there is no sample code and I'm not even sure I'm looking at the right thing.

Could anybody help me with this please?

Troy

In the case below, ASP.NET Ajax would deserialize the object to right type.

[WebMethod]
public string save(object obj)
{
obj.save() // obj is casted to one of several c# classes depending upon the __Type property present
}

However this only happens for the types that corrospond to type proxy that is generated (This way server side has control over what types can instantiated during deserialization). Please include [GenerateScriptType(typeof(YourType))] to your service class, for all the possible types that can be passed to 'save' webmethod.


In the case below, ASP.NET Ajax would deserialize the object to right type.

[WebMethod]
public string save(object obj)
{
obj.save() // obj is casted to one of several c# classes depending upon the __Type property present
}

However this only happens for the types that corrospond to type proxy that is generated (This way server side has control over what types can instantiated during deserialization). Please include [GenerateScriptType(typeof(YourType))] to your service class, for all the possible types that can be passed to 'save' webmethod.


Ankit,Thanks for your answer. However, I am still unsure where to continue from here. Obj is type object, a builtin C# type that I am using as a placeholder since I don't know what I am going to receive from the client. I can't call obj.save directly since it will try and call a save() method on the builtin object type (that doesn't exist). How do I coerce obj into thinking it is one of my allowable types? Moreover, the type that was actually received?

Also, I have added the [GenerateScriptType... decoration but I don't think it was needed. My classes were already successfully serialized to the client. When I inspect the DOM I can see all of my allowable classes and when I inspect the contents of the XHR post I see the full json text including __Type:

Troy


Sorry I somewhat misread your question ( I thought you said deserialization is not being handled properly by ASP.NET Ajax). Yes if the type is already referenced by your service class then you don't need the GenerateScriptType decoration.

Once you get Obj of type Object, you can call Obj.GetType() to get the type of the object. Based on the type you would need to cast to the type , and then call .save(). If you have control over the definations for all the types that you need to call .save() on , a better thing would be to define an interface with .save() method, and have all the types implement that interface.


Ankit, thank you so much. You've answered my first and most fundamental question which is "can it be done?" I understand conceptually what you are saying but I'm unsure how to actually implement it. I have control over all the interfaces. I have created an abstract class called Asset and then derived Bookmark and Collection from it. Both Bookmark and Collection override the abstract save() method. If you have the time would you be able to offer some sample code?

Thanks,

Troy


In a related question how can I go about ensuring the __Type property is present?

One of my webmethods is called getTemplate()

 [WebMethod] [ScriptMethod(UseHttpGet =true, ResponseFormat = ResponseFormat.Json)] [PrincipalPermission(SecurityAction.Demand, Role ="Users")]public adbeast.myadbeast.collection getTemplate() {return new adbeast.myadbeast.collection(); }

and it returns

{"__type":"adbeast.myadbeast.collection","collectionType":0,"id":0,"parentId":null,"title":"","description":"","urlIcon":"","ace":0,"assetsUpdated":false,"usernameCreated":"","usernameModified":"","dateCreated":"\/Date(-62135578800000)\/","dateUpdated":"\/Date(-62135578800000)\/","assetIds":{"BOOKMARK":[],"IMAGE":[],"NEWSSUBSCRIPTION":[],"SPOT":[]},"assetType":1}
I have another webmethod
  
 [WebMethod] [ScriptMethod(UseHttpGet =true, ResponseFormat = ResponseFormat.Json)] [PrincipalPermission(SecurityAction.Demand, Role ="Users")]public List getAssets(Int64[] arrAssetIds) {return adbeast.myadbeast.user.getAssets(currentUser.userName.ToString(), arrAssetIds); }
 that returns
 [{"collectionType":0,"id":72,"parentId":0,"title":"My Collection","description":"","urlIcon":"/thumbnails/","ace":31,"assetsUpdated":false,"usernameCreated":"troyf","usernameModified":"troyf","dateCreated":"\/Date(1179432532950)\/","dateUpdated":"\/Date(1179432577013)\/","assetIds":{"BOOKMARK":[92,93,94,95,96,70,71,70],"IMAGE":[],"NEWSSUBSCRIPTION":[],"SPOT":[]},"assetType":1}]  

I am not receiving the __Type property in the second example. Should I be writing a custom Converter for my classes? I am looking at http://ajax.asp.net/docs/mref/T_System_Web_Script_Serialization_JavaScriptSerializer.aspx and the examples but there is no indication that __Type is created if I build a custom converter.

Troy


Are both these methods in the same web service?


They are in separate webservices.

T.


Try adding [GenerateScriptType(typeof(adbeast.myadbeast.collection))] to the service class in second case. __type is only added for types that are for parameter types , return types for webmethods, and types in GenerateScriptType decorations.