Json and Circular Reference Exception

前端 未结 9 1641
挽巷
挽巷 2020-11-27 03:17

I have an object which has a circular reference to another object. Given the relationship between these objects this is the right design.

To Illustrate

9条回答
  •  星月不相逢
    2020-11-27 04:03

    Use to have the same problem. I have created a simple extension method, that "flattens" L2E objects into an IDictionary. An IDictionary is serialized correctly by the JavaScriptSerializer. The resulting Json is the same as directly serializing the object.

    Since I limit the level of serialization, circular references are avoided. It also will not include 1->n linked tables (Entitysets).

        private static IDictionary JsonFlatten(object data, int maxLevel, int currLevel) {
            var result = new Dictionary();
            var myType = data.GetType();
            var myAssembly = myType.Assembly;
            var props = myType.GetProperties();
            foreach (var prop in props) {
                // Remove EntityKey etc.
                if (prop.Name.StartsWith("Entity")) {
                    continue;
                }
                if (prop.Name.EndsWith("Reference")) {
                    continue;
                }
                // Do not include lookups to linked tables
                Type typeOfProp = prop.PropertyType;
                if (typeOfProp.Name.StartsWith("EntityCollection")) {
                    continue;
                }
                // If the type is from my assembly == custom type
                // include it, but flattened
                if (typeOfProp.Assembly == myAssembly) {
                    if (currLevel < maxLevel) {
                        result.Add(prop.Name, JsonFlatten(prop.GetValue(data, null), maxLevel, currLevel + 1));
                    }
                } else {
                    result.Add(prop.Name, prop.GetValue(data, null));
                }
            }
    
            return result;
        }
        public static IDictionary JsonFlatten(this Controller controller, object data, int maxLevel = 2) {
            return JsonFlatten(data, maxLevel, 1);
        }
    

    My Action method looks like this:

        public JsonResult AsJson(int id) {
            var data = Find(id);
            var result = this.JsonFlatten(data);
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    

提交回复
热议问题