1
votes

I am using Silverlight with WCF. I have a fairly complicated object that I am wanting to send to the server. This object is shared among multiple services and so cannot be a data contract. I am wondering if there is a simple way to do the serialization myself. A way that works for both .Net 4 (server side) and Silverlight 4 (client side).

Note, I am not using RIA Services, because RIA Services has been a huge pain in my side since I started using it.

Edits:

I've attempted to use the DataContractAttribute and DataMemberAttribute to no avail. I get the following exception from the service:

System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime.Serialization, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified. File name: 'System.Runtime.Serialization, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'

The reason seems evident. I believe it is because the DLL that contains the POCO is a Silverlight Class Library. This is the only way I know to share the object between both my WCF Service and my Silverlight Client. The problem, I believe, is that the Silverlight DLL is using the Silverlight version of System.Runtime.Serialization and therefore the POCO cannot be used in a non Silverlight environment. I have to share this POCO among multiple services so it has to exist in a separate Assembly.

This is why I want to control how I serialize my objects; serialize them inside the objects themselves.

2

2 Answers

2
votes

I would recommend Json.NET. You can download the NuGet package which has support for .Net and Silverlight.

Serialize:

string json = JsonConvert.SerializeObject(myObj);

Deserialize:

var myObj = JsonConvert.DeserializeObject<MyObject>(json);
1
votes

The DataContractSerializer supports POCO types both in Silverlight and in .NET 4.0. You can try it and it should just work.

Update after edits: You cannot reference a library built for Silverlight from .NET Framework, they reference different assemblies. You have a couple of options:

  • Create two Class Library projects, one for SL and another for the full framework. Add the files in one of the projects, and on the other simply add links to them. This I've done many times and works fine.
  • Create a Portable Library (PL) assembly. I haven't tried that, but that's exactly the goal of the PL - share assemblies between different .NET versions. You can try that to see if it works.