JSON.Net自定义合同序列化和集合

时间:2016-06-26 13:07:22

标签: c# json serialization asp.net-web-api json.net

我正在尝试创建一个IContractResolver来简化我在WebApi项目上的安全处理。

我在尝试什么:

我想根据一组动态条件序列化某些对象/属性(例如,调用端点的用户的角色)。

所以我实现了一个在Interface的CreateProperty覆盖中检查的自定义属性,并将ShouldSerialize函数设置为我自己的逻辑。

我现在的问题是,是否可以有条件地序列化某个列表中的完整对象?而不是在预处理步骤中过滤列表(这很容易出错,如果我更改了我的对象),我希望它由当前的ContractResolver递归处理。

在某种程度上,我试图得到这样的东西:

override void CreateObject(JSONObject ob){
if ( ob.DeclaringType == MyType)
{
   ob.ShouldSerialize = instance => {[...] }; //Custom Logic
}
}

我错过了覆盖,这根本不可能吗?有没有更好的方法来实际执行此操作,而无需我必须预先解析"我所有的价值观?

1 个答案:

答案 0 :(得分:2)

这不是开箱即用的。如果您检查JsonSerializerInternalWriter.SerializeList()的源,您将看到没有逻辑可以根据某些过滤器跳过集合条目。

但是,Json.NET确实有robust exception handling。如果在开始序列化对象时抛出异常,则在[OnError]回调中捕获并吞并:

  • 如果编写数组条目,则数组条目跳过(您想要的行为)。
  • 如果编写根对象,则不会捕获异常(可能是错误?)
  • 否则会写null

因此,实现所需功能的一种可能性是从自定义合约解析程序添加到JsonContract.OnSerializingCallbacks的人工回调中抛出异常,然后通过添加到JsonContract.OnErrorCallbacks的处理程序捕获并吞下异常。当您正在进行对属性值的过滤时,这种方法的优点是可以保证秘密对象即使是根对象或包含在字典,动态对象或多维数组中时也无法序列化。这种方法不会干扰PreserveReferencesHandling.Arrays

执行此操作的一个合同解析程序如下:

sealed class JsonSkipObjectException : JsonException
{
}

public class ShouldSerializeContractResolver : DefaultContractResolver
{
    readonly Predicate<object> shouldSerialize;
    readonly SerializationCallback serializationCallback;
    readonly SerializationErrorCallback onErrorCallback;

    public ShouldSerializeContractResolver(Predicate<object> shouldSerialize)
        : base()
    {
        this.shouldSerialize = shouldSerialize;
        this.serializationCallback = (o, context) =>
            {
                if (shouldSerialize != null && !this.shouldSerialize(o))
                    throw new JsonSkipObjectException();
            };
        this.onErrorCallback = (o, context, errorContext) =>
            {
                if (errorContext.Error is JsonSkipObjectException)
                {
                    errorContext.Handled = true;
                }
            };
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);

        if (shouldSerialize != null)
        {
            if (property.Readable)
            {
                var oldShouldSerialize = property.ShouldSerialize;
                property.ShouldSerialize = (o) =>
                    {
                        if (oldShouldSerialize != null && !oldShouldSerialize(o))
                            return false;
                        var value = property.ValueProvider.GetValue(o);
                        if (!this.shouldSerialize(value))
                            return false;
                        return true;
                    };
            }
        }
        return property;
    }

    protected override JsonContract CreateContract(Type objectType)
    {
        var contract = base.CreateContract(objectType);
        contract.OnSerializingCallbacks.Add(serializationCallback);
        contract.OnErrorCallbacks.Add(onErrorCallback);
        return contract;
    }
}

然后一个可能的用途是:

public interface IConditionalSerialization
{
    bool ShouldSerialize();
}

public class ConditionalSerializationObject : IConditionalSerialization
{
    public bool IsSecret { get; set; }

    public string SecretProperty { get { return "should not see me"; } }

    // Ensure "normal" conditional property serialization is not broken
    public bool ShouldSerializeSecretProperty()
    {
        return false;
    }

    #region IConditionalSerialization Members

    bool IConditionalSerialization.ShouldSerialize()
    {
        return !IsSecret;
    }

    #endregion
}

public class TestClass
{
    public static void Test()
    {
        Predicate<object> filter = (o) => 
            {
                var conditional = o as IConditionalSerialization;
                return conditional == null || conditional.ShouldSerialize();
            };
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new ShouldSerializeContractResolver(filter),
        };

        var ok = new ConditionalSerializationObject { IsSecret = false };
        var notOk = new ConditionalSerializationObject { IsSecret = true };

        Test(ok, settings);
        Test(new { Public = ok, Private = notOk }, settings);
        Test(new [] { ok, notOk, ok, notOk }, settings);
        Test(new[,] {{ ok, notOk, ok, notOk }}, settings);
        Test(new { Array = new[,] { { ok, notOk, ok, notOk } } }, settings);
        try
        {
            Test(notOk, settings);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception thrown and not caught serializing root object " + notOk.GetType());
            Console.WriteLine(ex);
        }
    }

    static void Test<T>(T value, JsonSerializerSettings settings)
    {
        Console.WriteLine("Unfiltered object: ");
        Console.WriteLine(JToken.FromObject(value));

        var serializer = JsonSerializer.CreateDefault(settings);
        var token = JToken.FromObject(value, serializer);
        Console.WriteLine("Filtered object: ");
        Console.WriteLine(token);
        if (!token.SelectTokens("..IsSecret").All(t => JToken.DeepEquals(t, (JValue)false)))
        {
            throw new InvalidOperationException("token.SelectTokens(\"..IsSecret\").All(t => JToken.DeepEquals(t, (JValue)true))");
        }
        if (token.SelectTokens("..SecretProperty").Any())
        {
            throw new InvalidOperationException("token.SelectTokens(\"..SecretProperty\").Any()");
        }
        Console.WriteLine("Secret objects and properties were successfully filtered.");
        Console.WriteLine("");
    }
}

原型fiddle

请注意,抛出和捕获大量异常会影响性能。见How expensive are exceptions in C#?。您需要对Web应用程序进行概要分析,以确定这是否是一个问题。在尝试序列化“秘密”时,您还需要确定您的Web服务是否应该返回异常。根对象,或做一些不同的事情。