5

以下のコードを使用して、DataContractJsonSerializer を使用して結果のリストを JSON に変換するにはどうすればよいですか?

ETA: オブジェクトを一般的に JSON 化する拡張メソッドをいくつか見てきましたが、これは匿名型であるため、どの型を使用すればよいかわかりません。

<Product> products = GetProductList();

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

ありがとう!

4

2 に答える 2

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.

于 2011-06-27T14:13:30.987 に答える
-1

少し前にここに貼り付けたコードは、json http://pastebin.com/cUX82cJCに何かをシリアライズする拡張メソッドです。

于 2011-06-27T14:09:59.687 に答える