How do you Serialize ScriptObjects to JSON to save in Silverlight Isolated Storage?
-
02-07-2019 - |
Question
According to this article Silverlight 2 Beta 2 supports the DataContractJsonSerializer
object. But, when I try to use it VS says
"Type 'DataContractJsonSerializer' is not defined".
I have a method marked as ScriptableMember that gets called from JavaScript and is passed an Object. Inside this method I need to serialize the object to a string (preferably JSON) and then save it in isolated storage.
Does Silverlight 2 Beta 2 really support DataContractJsonSerializer? Or would anyone recommend a different method of saving the JavaScript created ScriptObject in the Isolated Storage?
Solution
Actually the answer is, the DataContractJsonSerializer is part of Silverlight 2 Beta 2, but you need to add a reference to System.ServiceModel.Web to your Silverlight project to use it.
I didn't realize that you still needed to add dll references in Silverlight. I thought it automatically included everything in a similar way to how ASP.NET does.
OTHER TIPS
There is a Silverlight version of Json.NET that will serialize your objects to JSON. It doesn't require [DataContract] and [DataMember] attributes all over your objects.
For now, the only solution to this that I have found is to use the ASP.NET AJAX JavaScriptSerializer to do the JSON serialization/deserialization in JavaScript, and then just use Silverlight to store/retrieve the resulting string.
Sys.Serialization.JavaScriptSerializer.serialize(obj);
Sys.Serialization.JavaScriptSerializer.deserialize(json);
I would say your own answer would be the best approach. JavaScript is dead slow at doing stuff like that, so best you leave the serialization-part to ASP.NET.