2

私はclass Aそれから派生していSystem.Data.Objects.DataClasses.EntityObjectます。を使用してシリアル化しようとすると

var a = new A();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(a.GetType());
serializer.WriteObject(Response.OutputStream, a);  

エラーが発生します

TestController+A._Id' is not marked with OptionalFieldAttribute, thus indicating that it must be serialized. However, 'TestController+A' derives from a class marked with DataContractAttribute and an IsReference setting of 'True'. It is not possible to have required data members on IsReference classes. Either decorate 'TestController+A._Id' with OptionalFieldAttribute, or disable the IsReference setting on the appropriate parent class.

でフィールドを飾ってOptionalFieldAttribute

The type 'TestController+A' cannot be serialized to JSON because its IsReference setting is 'True'. The JSON format does not support references because there is no standardized format for representing references. To enable serialization, disable the IsReference setting on the type or an appropriate parent class of the type.

EntityObjectクラスを変更できません。A_Bagクラスをクラスとまったく同じように作成しA、それを埋めて、代わりにシリアル化することAを考えましたが、もっとエレガントな方法があると思います。

どうすればいいのか提案してもらえますか?

4

2 に答える 2

2

ここでは「データコントラクトサロゲート」を使用できると思います(IDataContractSurrogateインターフェイスを介して使用されます)。

データコントラクトサロゲートは、すでに使用しているデータコントラクトモデルに基づいて構築された高度な機能です。型のシリアル化、逆シリアル化、または(XMLを扱っている場合)スキーマへの射影方法を変更したい状況で、型のカスタマイズと置換を行うことができます。

あなたの場合、IDataContractSurrogateを使用すると、タイプごとまたはオブジェクトごとにカスタムJSONシリアル化および逆シリアル化を実行できます。IDataContractSurrogateは、シリアル化および逆シリアル化中にDataContractSJsonerializerによって1つのタイプを別のタイプに置き換えるために必要なメソッドを提供します。また、シナリオに別の「特別な」中間タイプを提供することもできます。

お役に立てれば!

于 2012-04-26T19:48:32.060 に答える
1

JSON.Net は、 でマークされたオブジェクトのシリアル化をサポートしていIsReference=trueます。

ここに詳細なチュートリアルがあります:

http://dotnet.learningtree.com/2012/04/03/working-with-the-entity-framework-and-the-web-api/

于 2012-07-10T17:31:39.450 に答える