我有一个包含DynamicObjects列表的类.我有一个单元测试,确认Newtonsoft Json Serializer / Deserializer正确处理这个问题.但是,默认的OData Json Serializer / Deserializer没有.
我实现了我自己的ODataEdmTypeDeserializer,如下所示:
public class JsonODataEdmTypeDeserializer : ODataEdmTypeDeserializer { public JsonODataEdmTypeDeserializer(ODataPayloadKind payloadKind) : base(payloadKind) { } public JsonODataEdmTypeDeserializer(ODataPayloadKind payloadKind,ODataDeserializerProvider deserializerProvider) : base(payloadKind,deserializerProvider) { } public override object Read(ODataMessageReader messageReader,Type type,ODataDeserializerContext readContext) { var data = readContext.Request.Content.ReadAsStringAsync().Result; //Call to the NewtonSoft Deserializer var ret = JsonConvert.DeserializeObject(data,type); return ret; } }
以及它的DefaultODataDeserializerProvider:
public class JsonODataDeserializerProvider : DefaultODataDeserializerProvider { public override ODataEdmTypeDeserializer GetEdmTypeDeserializer(IEdmTypeReference edmType) { var kind = GetODataPayloadKind(edmType); return new JsonODataEdmTypeDeserializer(kind,this); } private static ODataPayloadKind GetODataPayloadKind(IEdmTypeReference edmType) { switch (edmType.TypeKind()) { case EdmTypeKind.Entity: return ODataPayloadKind.Entry; case EdmTypeKind.Primitive: case EdmTypeKind.Complex: return ODataPayloadKind.Property; case EdmTypeKind.Collection: IEdmCollectionTypeReference collectionType = edmType.AsCollection(); return collectionType.ElementType().IsEntity() ? ODataPayloadKind.Feed : ODataPayloadKind.Collection; default: return ODataPayloadKind.Entry; } } }
这些工作正常,但是当我尝试创建自己的Serialize实现时遇到了障碍:
public class JsonODataEntityTypeSerializer : ODataEntityTypeSerializer { public JsonODataEntityTypeSerializer(ODataSerializerProvider serializerProvider) : base(serializerProvider) { } public override void WriteObject(object graph,ODataMessageWriter messageWriter,ODataSerializerContext writeContext) { }
当我的控制器试图返回有问题的对象时,会调用WriteObject,但我不知道该怎么做才能插入Newtonsoft Serializer.我下载了OData源代码并查看了它,但我没有看到我需要的钩子.
解决方法
您必须创建自定义DataWriter,例如NewtonsoftJsonDataWriter:ODataWriter.
看看那里:tutorial-sample-odatalib-custom-payload-format
在示例中,它是一个实现的Csv编写器,我认为您将能够使用简单的Json.Convert()覆盖其方法WriteStart,WriteHeader,WriteEntry和WriteEnd.