Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I serialize anonymous type using DataContractJsonSerializer [duplicate]

Using the code below, how can I use the DataContractJsonSerializer to convert the resultant list to JSON?

ETA: I have seen several extension methods to generically JSON-ize objects, but I'm not sure what type to use, as this is an anonymous type.

<Product> products = GetProductList();

var orderGroups =
 from p in products
 group p by p.Category into g
 select new { Category = g.Key, Products = g };

Thanks!

like image 736
Jon Avatar asked Nov 14 '22 21:11

Jon


1 Answers

You can't use a datacontract serializer to perform this serialization, because an anonymous type doesn't define any contract.

DataContractSerializers use [DataContract] and [DataMember] attributes to decide which properties should be serialized. However, as anonymous types are compiler generated, they can't receive attributes.

[DataContract]
class Data
{
    [DataMember]
    public string Category{get;set;}
    [...]
}

In fact, my opinion is that you are doing something wrong if your interfaces between client and server are defined through anonymous types.

You could certainly use another serializer to perform this task however, but I don't know of any serializing any public properties recursively without any annotations. ;)

EDIT: In fact I know exactly what you could use to serialize arbitrary (and therefore anonymous) classes into json. Use the marvellous Json.NET Library.

like image 187
Eilistraee Avatar answered Dec 19 '22 01:12

Eilistraee