【问题标题】:mvc4 webapi custom json serializer for specific type特定类型的 mvc4 webapi 自定义 json 序列化程序
【发布时间】:2013-03-09 06:32:55
【问题描述】:

我知道 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;

问候 菲尔

【问题讨论】:

    标签: asp.net-mvc json c#-4.0 deserialization json.net


    【解决方案1】:

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

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

    2. 创建一个自定义的 JsonResult 类,只需覆盖默认的类。你 也能够覆盖那里的默认序列化,即 继续。

      现在:

      • 当您已有 JSON 时,您可以排除此数据 序列化字符串...这将是最简单的选择。基本上只是字符串操作。
      • 另一方面,您还可以调用自定义 NewtonSoft 序列化,你可以在那里做任何你想做的事情......甚至使用自定义序列化。

    【讨论】:

    • 谢谢彼得,但我正在使用 WebApi,不想回到使用 JsonResult 封装的控制器基础
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 2014-06-08
    • 2017-02-05
    • 2021-09-21
    相关资源
    最近更新 更多