5

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!

dbc
  • 104,963
  • 20
  • 228
  • 340
Jon
  • 51
  • 1
  • 3

2 Answers2

2

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.

Eilistraee
  • 8,220
  • 1
  • 27
  • 30
-1

the code i pated here a while ago is an extension method that will serialize anything to json http://pastebin.com/cUX82cJC

harryovers
  • 3,087
  • 2
  • 34
  • 56
  • What would I pass as the type, as this is an anonymous type? – Jon Jun 27 '11 at 14:12
  • you wouldn't need to to serialize. you would just do `string jsonData = orderGroups.JsonSerialise();` – harryovers Jun 27 '11 at 14:43
  • Forgive me if I am misunderstanding how the `DataContractJsonSerializer` works but would this work with an anonymous type as it will not have any `DataContract` and `DataMember` attributes. – Ben Robinson Jun 27 '11 at 14:53
  • it maybe anonymouse but you should be able to tell what type your implementation will be and you can therefore go and add any `DataContract` and `DataMember` attributes – harryovers Jun 27 '11 at 14:56
  • there is also a similar question: http://stackoverflow.com/questions/331976/how-do-i-serialize-a-c-anonymous-type-to-a-json-string – harryovers Jun 27 '11 at 14:59
  • 1
    If the type is anonymous, you can't access the generated type, as it is compiler generated. (And not visible before compilation) – Eilistraee Jun 27 '11 at 22:42
  • the serialisation class only needs to know the type during runtime so it will be fine – harryovers Jun 28 '11 at 08:27