views:

248

answers:

2

Hi,

When I call a PageMethod in my page, the serialized object looks like: {"d":{"__type":"MyAsembly.MyNamespace.Person","Name":"ulu","Age":40}}

This is ok for Javascript, but my .Net deserializer won't understand it:

var result= new JavaScriptSerializer(new SimpleTypeResolver()).Deserialize<Person>(source);

throws System.InvalidOperationException: Operation is not valid due to the current state of the object.

Now, the actual problem is that the Activator can't create the result object: it doesn't understand "MyAsembly.MyNamespace.Person" and needs "MyAsembly.MyNamespace.Person, MyAssembly".

The question is, what do I need to change so that serialization becomes compatible with deserialization?

Thanks a lot ulu

A: 

Seems like you already know the answer: modify the value of the __type property before serializing the object on the JavaScript side. Alternatively, you could do a replace on the serialized data before pushing it through the deserializer.

Question though: where is the data being serialized? If you're doing it in .NET and then sending it to the client, it shouldn't need any modification when it gets back to the server unless something tampered with the __type property.

Rory
I can't modify it, I use PageMethods and just return a Person instance.
ulu
In that case it is very strange that there is not enough information to deserialize it. When you say that you can't modify it, have you tried using JavaScript? I ask because JavaScript does not have the notion of private fields, so `person.__type = 'MyAssembly.MyNamespace.Person, MyAssembly'` should actually update the field without a problem. BTW, which version of .NET are you targeting? Just took a look at the docs for 3.5 and noticed that JavaScriptSerializer has been deprecated in favour of `System.Runtime.Serialization.DataContractJsonSerializer`.
Rory
Ok, here's my situation. I'm building a framework for Asp.Net testing (Ivonna), and my current idea is to let people test page methods. So, I have no control over how the object is serialized. The framework gets the serialized string and tries to deserialize it back. At this point, I do have control over the string and am able to modify it. I can't use JavaScript, so I'll have to parse it manually.As for the DataContractJsonSerializer, it cannot deserialize the string that was serialized using JavaScriptSerializer (which, although deprecated, is used in page methods result serialization)
ulu
A: 

I am guessing that

{"d":{"__type":"MyAsembly.MyNamespace.Person","Name":"ulu","Age":40}}

should be

{"d":{"__type":"MyAssembly.MyNamespace.Person","Name":"ulu","Age":40}}
Mark Bertenshaw
Oops that's just a typo. The point is, you can't construct an object calling Activator.CreateInstance("MyAssembly.MyNamespace.Person")
ulu