4

我知道 MVC4 使用 NewtonSoft Json 反序列化。我想知道如何在不使用任何数据注释(如 JsonIgnore/DataMemberIngore 等)的情况下将序列化属性排除到客户端(该程序集在其他地方使用并且无法更改。我可以实现自定义格式化程序/JsonSerializerSettings/Dynamic ContractResolver等针对特定对象类型,然后过滤掉特定属性名称?

非常感谢任何帮助。

编辑。想出了以下作为第一次尝试。如果有人有更优雅的解决方案,请告诉我......

public class DynamicContractResolver : DefaultContractResolver
{
    public DynamicContractResolver()
    {

    }

    protected override IList<JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization)
    {

        IList<JsonProperty> properties = base.CreateProperties(type, Newtonsoft.Json.MemberSerialization.Fields);

        if (type == typeof(SomeType))
        {
            var matchedProp = properties.Where(v=> v.PropertyName=="SomeProperty").FirstOrDefault();
            if (matchedProp!=null)
            {
                properties.Remove(matchedProp);
            }
        }


        return properties;
    }
}

深入到 global.asax:

HttpConfiguration config = GlobalConfiguration.Configuration;
JsonSerializerSettings serializerSetting = new JsonSerializerSettings
        {
            ContractResolver = new DynamicContractResolver(),
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize
        };

config.Formatters.JsonFormatter.SerializerSettings = serializerSetting;

问候菲尔

4

1 回答 1

0

这可以通过适当的覆盖来解决

  1. 覆盖MVC类Json中的函数。Controller在这个类中,您可以自定义数据。(使用另一个映射,使用反射,...)

  2. 创建一个自定义的 JsonResult 类,只需覆盖默认的类。您还可以在那里覆盖正在进行的默认序列化。

    现在:

    • 当您已经有一个 JSON 序列化字符串时,您可以排除这些数据......这将是最简单的选择。基本上只是字符串操作。
    • 另一方面,您还可以调用自定义 NewtonSoft 序列化,您可以在那里做任何您想做的事情......甚至使用自定义序列化。
于 2013-03-09T06:55:38.450 回答