json - NHibernate json 代理序列化与 ReferencesAny

标签 json nhibernate

我有以下映射:

    public class TimeLineEntityMap : BaseEntityMap<TimeLineEntity>
    {
        public TimeLineEntityMap()
        {
            Table("time_line_entity");
            Map(x => x.Message);
            Map(x => x.ResearchId, "research_id");//.Cascade.All().Not.LazyLoad();
            ReferencesAny(x => x.EntityRef)
                .AddMetaValue<EmailEntity>(typeof(EmailEntity).Name)
                .AddMetaValue<UrlEntity>(typeof(UrlEntity).Name)
                .AddMetaValue<PhoneEntity>(typeof(PhoneEntity).Name)
                .EntityTypeColumn("entity_type")
                .IdentityType<long>()
                .EntityIdentifierColumn("entity_ref_id")
                .Not.LazyLoad();
        }
    }

从数据库获取时,EntityRef 作为代理。

TimeLineEntity res = timeLineRepository.Find(x => x.Id == id);
JsonConvert.SerializeObject(res);

JsonConvert 抛出异常:

Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'ManifestModule' with type 'System.Reflection.RuntimeModule'. Path 'Data[0].EntityRef._proxyFactoryInfo._getIdentifierMethod.Module.Assembly'.

这是我的 json 设置:

     x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
     x.SerializerSettings.ContractResolver = new NHibernateContractResolver();
    public class NHibernateContractResolver : CamelCasePropertyNamesContractResolver
    {
        protected override JsonContract CreateContract(Type objectType)
        {
            if (typeof(NHibernate.Proxy.INHibernateProxy).IsAssignableFrom(objectType))
                return base.CreateContract(objectType.BaseType);
            else
                return base.CreateContract(objectType);
        }
    }

最佳答案

尝试在模型类上添加 [JsonIgnore],如下所示:

[JsonIgnore]
public class TimeLineEntity {

}

更新 要获得它的序列化,您应该解析 map 的循环引用。

下面的链接会对您有所帮助。(可能您的答案已经存在。)

JSON.NET Error Self referencing loop detected for type

Resolve circular references from JSON object

Stringify (convert to JSON) a JavaScript object with circular reference

http://blogs.microsoft.co.il/gilf/2011/10/17/avoiding-circular-reference-for-entity-in-json-serialization/

祝你好运。

关于json - NHibernate json 代理序列化与 ReferencesAny,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58038635/

相关文章:

php - 有关 json 的更多帮助

javascript - 具有多个值的 json 对象的正确结构

java - Gson将float解析为int

c# - 为什么 ASP.NET Identity 的 `UserStore` 中有这么多存储库?

c# - LINQ 计算链接表中的行数

java - 为什么 Gson 期望开始数组却得到一个对象呢?

php - CodeIgniter:json_decode 数组问题

NHibernate AliasToBeanResultTransformer 和集合

nhibernate - 使用 ICriteria 按 null/not null 排序

nhibernate - 了解 Orchard 连接和数据关系