c# – 如何用NewtonSoft的Json Serializer替换OData V4默认的Json Serializer?

前端之家收集整理的这篇文章主要介绍了c# – 如何用NewtonSoft的Json Serializer替换OData V4默认的Json Serializer?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含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.

原文链接:https://www.f2er.com/csharp/100099.html

猜你在找的C#相关文章