【问题标题】:JSON.net JsonIgnoreAttribute not working with "EntityKey" propertyJSON.net JsonIgnoreAttribute 不适用于“EntityKey”属性
【发布时间】:2012-01-25 08:37:50
【问题描述】:

我正在使用 JSON.net 序列化我的 EntityFramework 对象。

过去,我创建了一个将“JsonIgnore”属性应用于属性的类,然后我将主 EntityFramework 类的“MetadataType”属性设置为新创建的类。

这是一个例子:

将应用于 EF 类的类:

 public class Role_DoNotSerialize
    {
        [JsonIgnore]
        public string Users { get; set; }
    }

EF 类的部分类文件:

[MetadataType(typeof(Role_DoNotSerialize))]
    public partial class Role
    { 
    }

在上面的例子中,当序列化一个“角色”对象时,属性“用户”不会被序列化。

我的问题是,当我像这样添加 EntityKey 属性时,同样的技术无法工作:

public class Role_DoNotSerialize
    {
        [JsonIgnore]
        public string Users { get; set; }

        [JsonIgnore]
        public System.Data.EntityKey EntityKey { get; set; }
    }

使用这个类,“EntityKey”属性仍然是序列化的。我做错了什么?

【问题讨论】:

  • 编写良好且工作良好的代码。好吧,就是应该工作的两个最高位。
  • 用你的问题找到了我的问题的答案!+1

标签: json entity-framework serialization json.net


【解决方案1】:

我认为 JSON.NET 的最新版本现在兑现了这一点。此示例在 MVC 站点中为我们工作,但您可以随意使用字符串。

public ActionResult ContentJsonFormatted(object obj, Formatting formatting = Formatting.Indented)
{
    string result = JsonConvert.SerializeObject(obj, formatting);
    return Content(result, "text/plain");
}

【讨论】:

    【解决方案2】:

    您可以通过实现自己的 ContractResolver 来做到这一点(示例代码使用 JSON.NET 4.5,但也可以使用旧版本)

    public class ExcludeEntityKeyContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type,memberSerialization);
            return properties.Where(p => p.PropertyType != typeof (System.Data.EntityKey)).ToList();
        }
    }
    

    然后你可以设置它来为你的 JsonSerializerSettings 对象设置 ContractResolver

    JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
    serializerSettings.ContractResolver = new ExcludeEntityKeyContractResolver();
    

    请注意,您不仅限于一个 lambda 函数,还可以实现任何类型的检查。您甚至可以覆盖每个属性的 Converter 来进行自定义序列化。

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 1970-01-01
      • 2014-05-21
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 2021-06-11
      相关资源
      最近更新 更多