0

i have this method to serialize my objects :

    private static byte[] GetBytes(object obj) {
        byte[] result;
        using (MemoryStream ms = new MemoryStream()) {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());

            ser.WriteObject(ms, obj);
            result = ms.ToArray();
            ms.Close();
        }
        return result;
    }

it is normal, when i want to use this, my object parameter must a class that decorate with [System.Runtime.Serialization.DataContract] and its member must decorate with [System.Runtime.Serialization.DataMember] but how about when i want to use unknown type like :

var myVar = GetBytes(new { Name = "MyName", LastName = "LastName" });

how can i decorate unknown types with attribute

Emran Sadeghi
  • 612
  • 6
  • 20

1 Answers1

1

DataContractJsonSerializer does not work with Anonymous Types. Consider simply sending a Dictionary over the wire if defining a specific Type with DataContract is not possible/justified.

Take a look at this thread also How do I serialize a C# anonymous type to a JSON string?.

Community
  • 1
  • 1
atomaras
  • 2,468
  • 2
  • 19
  • 28
  • link that you sent me, some one say use JavaScriptSerializer and this class is in System.Web.Extensions.dll, but i cannot use it in Silverlight, other one say use Newtonsoft JSON.NET but also this cannot use in Silverlight, thanks – Emran Sadeghi Dec 10 '13 at 07:01
  • Quote : "Json.NET supports Windows, Silverlight, Windows Phone, Mono, MonoTouch and MonoDroid" – atomaras Dec 10 '13 at 08:03
  • yes i must use Portable40 version, thanks – Emran Sadeghi Dec 10 '13 at 08:12