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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With