Richie 的个人资料The Sandpit - "We hack s...日志列表 工具 帮助
4月1日

Silverlight Serialization to JSON

This post will walkthrough the process of serializing and de-serializing an object to/from a JSON using Silverlight.

Starting from a new Silverlight Application, add references to the System.Runtime.Serialization and System.ServiceModel.Web assemblies.

 image

At the top of the Page.xaml.cs code page, add the highlighted using statements.

 image

Still in the Page.xaml.cs code page, add a definition of a Person class that we will ultimately serialize to JSON.  The class must be attributed with DataContract, a flag that denotes that the class (and all public members) are serializable.  In the screenshot below, I have explicitly added DataMember attributes to shorten the property names in the JSON string.

image

Add a Button to the XAML and add an event handler for the click event, so that the code in Page.xaml.cs looks like the following.

image 

Within the Button_Click method, let’s start by creating a new instance of the Person class.

image

Using DataContractJsonSerializer the person object can be converted to a JSON string.

image

Let’s add a message box to display the JSON string.

image

Now let’s convert the JSON string (denoted by the “json” variable) back into a Person object (denoted by “person2”).

image

Lastly, just to confirm that de-serialized object is correct, display the property values of “person2”.

image 

The final step is to run this code and see if it works!  Run the application in debug and click on the button you defined above to execute the serialization code.  The first popup displays the serialized Person as a JSON string.  The JSON is using the shorter member names defined using the DataMember attribute.

image

The second popup displays properties from the de-serialized person.

image 

评论 (1)

请稍候...
很抱歉,您输入的评论太长。请缩短您的评论。
您没有输入任何内容,请重试。
很抱歉,我们当前无法添加您的评论。请稍后重试。
若要添加评论,需要您的家长授予您相应权限。请求权限
您的家长禁用了评论功能。
很抱歉,我们当前无法删除您的评论。请稍后重试。
您已超过了一天之内允许提供的评论数上限。请在 24 小时后重试。
因为我们的系统表明您可能在向其他用户提供垃圾评论,您的帐户已禁用了评论功能。如果您认为我们错误地禁用了您的帐户,请联系 Windows Live 支持部门
完成下面的安全检查,您提供评论的过程才能完成。
您在安全检查中键入的字符必须与图片或音频中的字符一致。
Carmichael​Richie 在此页禁用了评论功能。
Morten just brought my attention to System.Json.dll which has coarse grained objects for serializing and deserealizing json. Thanks Morten!

Creating JSON:

System.Json.JsonObject values = new System.Json.JsonObject();
values.Add("extent", new System.Json.JsonArray(extent.XMin, extent.YMin, extent.XMax, extent.YMax ));
values.Add("filter", filter);
values.Add("page", page);
string jsonString = values.ToString();

Recreating it (not as straightforward, but still… An extension method could make this simpler):

System.Json.JsonObject values = System.Json.JsonObject.Load(myTextReaderOrStream);
JsonObject obj = null;
values.TryGetValue["filter", obj];
string value = (string)obj;

…you can also use .Parse(jsonString) of you don’t have a stream but just the string.
4 月 8 日

引用通告

引用此项的网络日志