JSON。为类型检测到的净错误自引用循环

时间:2021-09-10 20:38:28

I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used

我尝试序列化从实体数据模型.edmx和使用时自动生成的POCO类

JsonConvert.SerializeObject 

I got the following error:

我得到以下错误:

Error Self referencing loop detected for type System.data.entity occurs .

检测到类型System.data的自引用循环错误。实体出现。

How do I solve this problem?

我如何解决这个问题?

16 个解决方案

#1


269  

That was the best solution http://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7

这是最好的解决方案http://code.msdn.microsoft.com/loop-reference -handling-in caaffaf7

Fix 1: Ignoring circular reference globally

(I have chosen/tried this one, as have many others)

(我和许多其他人一样,选择了/尝试了这个)

The json.net serializer has an option to ignore circular references. Put the following code in WebApiConfig.cs file:

json.net序列化器有一个选项可以忽略循环引用。将下面的代码放到WebApiConfig中。cs文件:

 config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
= Newtonsoft.Json.ReferenceLoopHandling.Ignore; 

The simple fix will make serializer to ignore the reference which will cause a loop. However, it has limitations:

简单的修复将使序列化器忽略将导致循环的引用。然而,它有一定的局限性:

The data loses the looping reference information The fix only applies to JSON.net The level of references can't be controlled if there is a deep reference chain

数据丢失了循环引用信息,该修复只适用于JSON.net。如果存在深度引用链,则无法控制引用级别

If you want to use this fix in a non-api ASP.NET project, you can add the above line to Global.asax.cs, but first add:

如果您想在非api ASP中使用此修复。NET项目,你可以添加上面的线到Global.asax。cs,但首先添加:

var config = GlobalConfiguration.Configuration;

Fix 2: Preserving circular reference globally

This second fix is similar to the first. Just change the code to:

第二个修复与第一个类似。只需将代码更改为:

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
     = Newtonsoft.Json.ReferenceLoopHandling.Serialize;     
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling 
     = Newtonsoft.Json.PreserveReferencesHandling.Objects;

The data shape will be changed after applying this setting.

应用此设置后,将更改数据形状。

[
   {
      "$id":"1",
      "Category":{
         "$id":"2",
         "Products":[
            {
               "$id":"3",
               "Category":{
                  "$ref":"2"
               },
               "Id":2,
               "Name":"Yogurt"
            },
            {
               "$ref":"1"
            }
         ],
         "Id":1,
         "Name":"Diary"
      },
      "Id":1,
      "Name":"Whole Milk"
   },
   {
      "$ref":"3"
   }
]

The $id and $ref keeps the all the references and makes the object graph level flat, but the client code needs to know the shape change to consume the data and it only applies to JSON.NET serializer as well.

$id和$ref保存了所有的引用并使对象图级别为平,但是客户端代码需要知道形状更改以消耗数据,并且它只适用于JSON。净序列化器。

Fix 3: Ignore and preserve reference attributes

This fix is decorate attributes on model class to control the serialization behavior on model or property level. To ignore the property:

这个修复是在模型类上修饰属性来控制模型或属性级别上的序列化行为。忽略属性:

1: public class Category 
   2: { 
   3:     public int Id { get; set; } 
   4:     public string Name { get; set; } 
   5:     
   6:     [JsonIgnore] 
   7:     [IgnoreDataMember] 
   8:     public virtual ICollection<Product> Products { get; set; } 
   9: } 

JsonIgnore is for JSON.NET and IgnoreDataMember is for XmlDCSerializer. To preserve reference:

JsonIgnore是JSON。NET和IgnoreDataMember是XmlDCSerializer的值。保存参考:

1: // Fix 3 
   2: [JsonObject(IsReference = true)] 
   3: public class Category 
   4: { 
   5:     public int Id { get; set; } 
   6:     public string Name { get; set; } 
   7:  
   8:     // Fix 3 
   9:     //[JsonIgnore] 
  10:     //[IgnoreDataMember] 
  11:     public virtual ICollection<Product> Products { get; set; } 
  12: } 
  13:  
  14: [DataContract(IsReference = true)] 
  15: public class Product 
  16: { 
  17:     [Key] 
  18:     public int Id { get; set; } 
  19:  
  20:     [DataMember] 
  21:     public string Name { get; set; } 
  22:  
  23:     [DataMember] 
  24:     public virtual Category Category { get; set; } 
  25: } 

JsonObject(IsReference = true)]is for JSON.NET and [DataContract(IsReference = true)] is for XmlDCSerializer. Note that: after applying DataContract on class, you need to add DataMember to properties that you want to serialize.

JsonObject(IsReference = true)是JSON。NET和[DataContract(IsReference = true)]用于XmlDCSerializer。注意:在对类应用DataContract之后,需要向要序列化的属性添加DataMember。

The attributes can be applied on both json and xml serializer and gives more controls on model class.

属性可以应用到json和xml序列化器上,并提供关于模型类的更多控件。

#2


374  

Use JsonSerializerSettings

使用JsonSerializerSettings

  • ReferenceLoopHandling.Error (default) will error if a reference loop is encountered. This is why you get an exception.
  • ReferenceLoopHandling。如果遇到引用循环,将发生错误(默认)。这就是为什么会出现异常。
  • ReferenceLoopHandling.Serialize is useful if objects are nested but not indefinitely.
  • ReferenceLoopHandling。如果对象是嵌套的,但不是无限嵌套的,那么序列化是有用的。
  • ReferenceLoopHandling.Ignore will not serialize an object if it is a child object of itself.
  • ReferenceLoopHandling。如果忽略对象本身是子对象,则不会序列化该对象。

Example:

例子:

JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
new JsonSerializerSettings { 
        ReferenceLoopHandling = ReferenceLoopHandling.Serialize
});

Should you have to serialize an object that is nested indefinitely you can use PreserveObjectReferences to avoid a *Exception.

如果您必须序列化一个嵌套不确定的对象,您可以使用PreserveObjectReferences来避免*Exception。

Example:

例子:

JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
new JsonSerializerSettings { 
        PreserveReferencesHandling = PreserveReferencesHandling.Objects
});

Pick what makes sense for the object you are serializing.

选择要序列化的对象的意义。

Reference http://james.newtonking.com/json/help/

参考http://james.newtonking.com/json/help/

#3


36  

The fix is to ignore loop references and not to serialize them. This behaviour is specified in JsonSerializerSettings.

修复方法是忽略循环引用,而不是序列化它们。此行为在JsonSerializerSettings中指定。

Single JsonConvert with an overload:

带有重载的单个JsonConvert:

JsonConvert.SerializeObject(YourObject, Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

Global Setting with code in Application_Start() in Global.asax.cs:

Global.asax.cs中的Application_Start()代码的全局设置:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

参考:https://github.com/JamesNK/Newtonsoft.Json/issues/78

#4


28  

Simplest way to do this is to add [JsonIgnore] to the virtual property in the class, for example:

最简单的方法是将[JsonIgnore]添加到类中的虚拟属性,例如:

    public string Name { get; set; }
    public string Description { get; set; }
    public Nullable<int> Project_ID { get; set; }

    [JsonIgnore]
    public virtual Project Project { get; set; }

Although these days, I create a model with only the properties I want passed through so it's lighter, doesn't include unwanted collections, and I don't lose my changes when I rebuild the generated files...

虽然现在,我创建了一个只有我想要传递的属性的模型,因此它更轻,不包含不需要的集合,并且当我重新构建生成的文件时,我不会丢失我的更改……

#5


20  

In .NET Core 1.0, you can set this as a global setting in your Startup.cs file:

在。net核心1.0中,您可以将其设置为启动时的全局设置。cs文件:

using System.Buffers;
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json;

// beginning of Startup class

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.OutputFormatters.Clear();
            options.OutputFormatters.Add(new JsonOutputFormatter(new JsonSerializerSettings(){
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            }, ArrayPool<char>.Shared));
        });
    }

#6


5  

We can add these two lines into DbContext class constructor to disable Self referencing loop, like

我们可以将这两行添加到DbContext类构造函数中,以禁用自引用循环,比如

public TestContext()
        : base("name=TestContext")
{
    this.Configuration.LazyLoadingEnabled = false;
    this.Configuration.ProxyCreationEnabled = false;
}

#7


4  

You can apply an attribute to the property too. The [JsonProperty( ReferenceLoopHandling = ... )] attribute is well suited to this.

您也可以对属性应用属性。JsonProperty(ReferenceLoopHandling =…)属性非常适合这种情况。

For example:

例如:

/// <summary>
/// Represents the exception information of an event
/// </summary>
public class ExceptionInfo
{
    // ...code omitted for brevity...

    /// <summary>
    /// An inner (nested) error.
    /// </summary>
    [JsonProperty( ReferenceLoopHandling = ReferenceLoopHandling.Ignore, IsReference = true )]
    public ExceptionInfo Inner { get; set; }

    // ...code omitted for brevity...    
}

Hope that helps, Jaans

希望有所帮助,扬

#8


3  

To ignore loop references and not to serialize them globally in MVC 6 use the following in startup.cs:

要忽略循环引用,不要在MVC 6中对它们进行全局序列化,请在startup.cs中使用以下方法:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().Configure<MvcOptions>(options =>
        {
            options.OutputFormatters.RemoveTypesOf<JsonOutputFormatter>();
            var jsonOutputFormatter = new JsonOutputFormatter();
            jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            options.OutputFormatters.Insert(0, jsonOutputFormatter);
        });
    }

#9


2  

Use this in WebApiConfig.cs class :

使用这个WebApiConfig。计算机科学类:

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

#10


2  

For me I had to go a different route. Instead of trying to fix the JSON.Net serializer I had to go after the Lazy Loading on my datacontext.

对我来说,我必须走另一条路。而不是试图修复JSON。Net serializer我必须在datacontext的延迟加载之后执行。

I just added this to my base repository:

我只是把它添加到我的基本库中:

context.Configuration.ProxyCreationEnabled = false;

The "context" object is a constructor parameter I use in my base repository because I use dependency injection. You could change the ProxyCreationEnabled property anywhere you instantiate your datacontext instead.

“上下文”对象是我在基本存储库中使用的构造函数参数,因为我使用依赖项注入。您可以在实例化datacontext的任何地方更改ProxyCreationEnabled属性。

http://techie-tid-bits.blogspot.com/2015/09/jsonnet-serializer-and-error-self.html

http://techie-tid-bits.blogspot.com/2015/09/jsonnet-serializer-and-error-self.html

#11


2  

To serialize usin NEWTONSOFTJSON when you have loop issue, in my case I did not need modify global.asax or either apiconfig. I just use JsonSerializesSettings ignoring Looping handling.

要在出现循环问题时序列化NEWTONSOFTJSON中的usin,我不需要修改全局。asax或者apiconfig。我只是使用JsonSerializesSettings来忽略循环处理。

JsonSerializerSettings jss = new JsonSerializerSettings();
jss.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var lst = db.shCards.Where(m => m.CardID == id).ToList();
string json = JsonConvert.SerializeObject(lst, jss);

#12


1  

I had this exception and my working solution is Easy and Simple,

我有这个例外,我的工作解决方案简单易行,

Ignore the Referenced property by adding the JsonIgnore attribute to it:

通过添加JsonIgnore属性来忽略引用的属性:

[JsonIgnore]
public MyClass currentClass { get; set; }

Reset the property when you Deserialize it:

反序列化时重置属性:

Source = JsonConvert.DeserializeObject<MyObject>(JsonTxt);
foreach (var item in Source)
        {
            Source.MyClass = item;
        }

using Newtonsoft.Json;

使用Newtonsoft.Json;

#13


1  

If you're using .NET Core 2.0, update your ConfigureServices section in Startup.cs

如果您使用的是。net核心2.0,请在Startup.cs中更新您的配置服务部分。

https://docs.microsoft.com/en-us/ef/core/querying/related-data#related-data-and-serialization

https://docs.microsoft.com/en-us/ef/core/querying/related-data related-data-and-serialization

public void ConfigureServices(IServiceCollection services)
{
...

services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );

...
}

#14


0  

Simply place Configuration.ProxyCreationEnabled = false; inside the context file; this will solve the problem.

简单的配置。ProxyCreationEnabled = false;在上下文文件;这将解决问题。

public demEntities()
    : base("name=demEntities")
{
    Configuration.ProxyCreationEnabled = false;
}

#15


-1  

For not looping this worked for me-
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,

对于没有循环的我来说这是可行的- ReferenceLoopHandling = referenceloophandling.忽略,

I've solved it all here - Entity Framework children serialization with .Net Core 2 WebAPI https://gist.github.com/Kaidanov/f9ad0d79238494432f32b8407942c606

我在这里已经解决了这一切-实体框架子序列化与。net Core 2 WebAPI https://gist.github.com/Kaidanov/f9ad0d79238494432f32b8407942c606

Will appreciate any remarks. maybe someone can use it sometime.

会欣赏任何言论。也许有人什么时候可以用它。

#16


-2  

I liked the solution that does it from Application_Start() as in the answer here

我喜欢Application_Start()中的解决方案,就像这里的答案一样

Apparently I could not access the json objects in JavaScript using the configuration within my function as in DalSoft's answer as the object returned had "\n \r" all over the (key, val) of the object.

显然,我不能使用函数中的配置访问JavaScript中的json对象,就像DalSoft的答案一样,因为返回的对象在对象的(key, val)上都有“\n \r”。

Anyway whatever works is great (because different approaches work in different scenario based on the comments and questions asked) though a standard way of doing it would be preferable with some good documentation supporting the approach.

不管怎样,任何有用的东西都很好(因为不同的方法在不同的场景中根据所询问的评论和问题进行工作),但是如果有一些好的文档支持这种方法,最好使用标准的方法。

#1


269  

That was the best solution http://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7

这是最好的解决方案http://code.msdn.microsoft.com/loop-reference -handling-in caaffaf7

Fix 1: Ignoring circular reference globally

(I have chosen/tried this one, as have many others)

(我和许多其他人一样,选择了/尝试了这个)

The json.net serializer has an option to ignore circular references. Put the following code in WebApiConfig.cs file:

json.net序列化器有一个选项可以忽略循环引用。将下面的代码放到WebApiConfig中。cs文件:

 config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
= Newtonsoft.Json.ReferenceLoopHandling.Ignore; 

The simple fix will make serializer to ignore the reference which will cause a loop. However, it has limitations:

简单的修复将使序列化器忽略将导致循环的引用。然而,它有一定的局限性:

The data loses the looping reference information The fix only applies to JSON.net The level of references can't be controlled if there is a deep reference chain

数据丢失了循环引用信息,该修复只适用于JSON.net。如果存在深度引用链,则无法控制引用级别

If you want to use this fix in a non-api ASP.NET project, you can add the above line to Global.asax.cs, but first add:

如果您想在非api ASP中使用此修复。NET项目,你可以添加上面的线到Global.asax。cs,但首先添加:

var config = GlobalConfiguration.Configuration;

Fix 2: Preserving circular reference globally

This second fix is similar to the first. Just change the code to:

第二个修复与第一个类似。只需将代码更改为:

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
     = Newtonsoft.Json.ReferenceLoopHandling.Serialize;     
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling 
     = Newtonsoft.Json.PreserveReferencesHandling.Objects;

The data shape will be changed after applying this setting.

应用此设置后,将更改数据形状。

[
   {
      "$id":"1",
      "Category":{
         "$id":"2",
         "Products":[
            {
               "$id":"3",
               "Category":{
                  "$ref":"2"
               },
               "Id":2,
               "Name":"Yogurt"
            },
            {
               "$ref":"1"
            }
         ],
         "Id":1,
         "Name":"Diary"
      },
      "Id":1,
      "Name":"Whole Milk"
   },
   {
      "$ref":"3"
   }
]

The $id and $ref keeps the all the references and makes the object graph level flat, but the client code needs to know the shape change to consume the data and it only applies to JSON.NET serializer as well.

$id和$ref保存了所有的引用并使对象图级别为平,但是客户端代码需要知道形状更改以消耗数据,并且它只适用于JSON。净序列化器。

Fix 3: Ignore and preserve reference attributes

This fix is decorate attributes on model class to control the serialization behavior on model or property level. To ignore the property:

这个修复是在模型类上修饰属性来控制模型或属性级别上的序列化行为。忽略属性:

1: public class Category 
   2: { 
   3:     public int Id { get; set; } 
   4:     public string Name { get; set; } 
   5:     
   6:     [JsonIgnore] 
   7:     [IgnoreDataMember] 
   8:     public virtual ICollection<Product> Products { get; set; } 
   9: } 

JsonIgnore is for JSON.NET and IgnoreDataMember is for XmlDCSerializer. To preserve reference:

JsonIgnore是JSON。NET和IgnoreDataMember是XmlDCSerializer的值。保存参考:

1: // Fix 3 
   2: [JsonObject(IsReference = true)] 
   3: public class Category 
   4: { 
   5:     public int Id { get; set; } 
   6:     public string Name { get; set; } 
   7:  
   8:     // Fix 3 
   9:     //[JsonIgnore] 
  10:     //[IgnoreDataMember] 
  11:     public virtual ICollection<Product> Products { get; set; } 
  12: } 
  13:  
  14: [DataContract(IsReference = true)] 
  15: public class Product 
  16: { 
  17:     [Key] 
  18:     public int Id { get; set; } 
  19:  
  20:     [DataMember] 
  21:     public string Name { get; set; } 
  22:  
  23:     [DataMember] 
  24:     public virtual Category Category { get; set; } 
  25: } 

JsonObject(IsReference = true)]is for JSON.NET and [DataContract(IsReference = true)] is for XmlDCSerializer. Note that: after applying DataContract on class, you need to add DataMember to properties that you want to serialize.

JsonObject(IsReference = true)是JSON。NET和[DataContract(IsReference = true)]用于XmlDCSerializer。注意:在对类应用DataContract之后,需要向要序列化的属性添加DataMember。

The attributes can be applied on both json and xml serializer and gives more controls on model class.

属性可以应用到json和xml序列化器上,并提供关于模型类的更多控件。

#2


374  

Use JsonSerializerSettings

使用JsonSerializerSettings

  • ReferenceLoopHandling.Error (default) will error if a reference loop is encountered. This is why you get an exception.
  • ReferenceLoopHandling。如果遇到引用循环,将发生错误(默认)。这就是为什么会出现异常。
  • ReferenceLoopHandling.Serialize is useful if objects are nested but not indefinitely.
  • ReferenceLoopHandling。如果对象是嵌套的,但不是无限嵌套的,那么序列化是有用的。
  • ReferenceLoopHandling.Ignore will not serialize an object if it is a child object of itself.
  • ReferenceLoopHandling。如果忽略对象本身是子对象,则不会序列化该对象。

Example:

例子:

JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
new JsonSerializerSettings { 
        ReferenceLoopHandling = ReferenceLoopHandling.Serialize
});

Should you have to serialize an object that is nested indefinitely you can use PreserveObjectReferences to avoid a *Exception.

如果您必须序列化一个嵌套不确定的对象,您可以使用PreserveObjectReferences来避免*Exception。

Example:

例子:

JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
new JsonSerializerSettings { 
        PreserveReferencesHandling = PreserveReferencesHandling.Objects
});

Pick what makes sense for the object you are serializing.

选择要序列化的对象的意义。

Reference http://james.newtonking.com/json/help/

参考http://james.newtonking.com/json/help/

#3


36  

The fix is to ignore loop references and not to serialize them. This behaviour is specified in JsonSerializerSettings.

修复方法是忽略循环引用,而不是序列化它们。此行为在JsonSerializerSettings中指定。

Single JsonConvert with an overload:

带有重载的单个JsonConvert:

JsonConvert.SerializeObject(YourObject, Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

Global Setting with code in Application_Start() in Global.asax.cs:

Global.asax.cs中的Application_Start()代码的全局设置:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

参考:https://github.com/JamesNK/Newtonsoft.Json/issues/78

#4


28  

Simplest way to do this is to add [JsonIgnore] to the virtual property in the class, for example:

最简单的方法是将[JsonIgnore]添加到类中的虚拟属性,例如:

    public string Name { get; set; }
    public string Description { get; set; }
    public Nullable<int> Project_ID { get; set; }

    [JsonIgnore]
    public virtual Project Project { get; set; }

Although these days, I create a model with only the properties I want passed through so it's lighter, doesn't include unwanted collections, and I don't lose my changes when I rebuild the generated files...

虽然现在,我创建了一个只有我想要传递的属性的模型,因此它更轻,不包含不需要的集合,并且当我重新构建生成的文件时,我不会丢失我的更改……

#5


20  

In .NET Core 1.0, you can set this as a global setting in your Startup.cs file:

在。net核心1.0中,您可以将其设置为启动时的全局设置。cs文件:

using System.Buffers;
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json;

// beginning of Startup class

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.OutputFormatters.Clear();
            options.OutputFormatters.Add(new JsonOutputFormatter(new JsonSerializerSettings(){
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            }, ArrayPool<char>.Shared));
        });
    }

#6


5  

We can add these two lines into DbContext class constructor to disable Self referencing loop, like

我们可以将这两行添加到DbContext类构造函数中,以禁用自引用循环,比如

public TestContext()
        : base("name=TestContext")
{
    this.Configuration.LazyLoadingEnabled = false;
    this.Configuration.ProxyCreationEnabled = false;
}

#7


4  

You can apply an attribute to the property too. The [JsonProperty( ReferenceLoopHandling = ... )] attribute is well suited to this.

您也可以对属性应用属性。JsonProperty(ReferenceLoopHandling =…)属性非常适合这种情况。

For example:

例如:

/// <summary>
/// Represents the exception information of an event
/// </summary>
public class ExceptionInfo
{
    // ...code omitted for brevity...

    /// <summary>
    /// An inner (nested) error.
    /// </summary>
    [JsonProperty( ReferenceLoopHandling = ReferenceLoopHandling.Ignore, IsReference = true )]
    public ExceptionInfo Inner { get; set; }

    // ...code omitted for brevity...    
}

Hope that helps, Jaans

希望有所帮助,扬

#8


3  

To ignore loop references and not to serialize them globally in MVC 6 use the following in startup.cs:

要忽略循环引用,不要在MVC 6中对它们进行全局序列化,请在startup.cs中使用以下方法:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().Configure<MvcOptions>(options =>
        {
            options.OutputFormatters.RemoveTypesOf<JsonOutputFormatter>();
            var jsonOutputFormatter = new JsonOutputFormatter();
            jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            options.OutputFormatters.Insert(0, jsonOutputFormatter);
        });
    }

#9


2  

Use this in WebApiConfig.cs class :

使用这个WebApiConfig。计算机科学类:

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

#10


2  

For me I had to go a different route. Instead of trying to fix the JSON.Net serializer I had to go after the Lazy Loading on my datacontext.

对我来说,我必须走另一条路。而不是试图修复JSON。Net serializer我必须在datacontext的延迟加载之后执行。

I just added this to my base repository:

我只是把它添加到我的基本库中:

context.Configuration.ProxyCreationEnabled = false;

The "context" object is a constructor parameter I use in my base repository because I use dependency injection. You could change the ProxyCreationEnabled property anywhere you instantiate your datacontext instead.

“上下文”对象是我在基本存储库中使用的构造函数参数,因为我使用依赖项注入。您可以在实例化datacontext的任何地方更改ProxyCreationEnabled属性。

http://techie-tid-bits.blogspot.com/2015/09/jsonnet-serializer-and-error-self.html

http://techie-tid-bits.blogspot.com/2015/09/jsonnet-serializer-and-error-self.html

#11


2  

To serialize usin NEWTONSOFTJSON when you have loop issue, in my case I did not need modify global.asax or either apiconfig. I just use JsonSerializesSettings ignoring Looping handling.

要在出现循环问题时序列化NEWTONSOFTJSON中的usin,我不需要修改全局。asax或者apiconfig。我只是使用JsonSerializesSettings来忽略循环处理。

JsonSerializerSettings jss = new JsonSerializerSettings();
jss.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var lst = db.shCards.Where(m => m.CardID == id).ToList();
string json = JsonConvert.SerializeObject(lst, jss);

#12


1  

I had this exception and my working solution is Easy and Simple,

我有这个例外,我的工作解决方案简单易行,

Ignore the Referenced property by adding the JsonIgnore attribute to it:

通过添加JsonIgnore属性来忽略引用的属性:

[JsonIgnore]
public MyClass currentClass { get; set; }

Reset the property when you Deserialize it:

反序列化时重置属性:

Source = JsonConvert.DeserializeObject<MyObject>(JsonTxt);
foreach (var item in Source)
        {
            Source.MyClass = item;
        }

using Newtonsoft.Json;

使用Newtonsoft.Json;

#13


1  

If you're using .NET Core 2.0, update your ConfigureServices section in Startup.cs

如果您使用的是。net核心2.0,请在Startup.cs中更新您的配置服务部分。

https://docs.microsoft.com/en-us/ef/core/querying/related-data#related-data-and-serialization

https://docs.microsoft.com/en-us/ef/core/querying/related-data related-data-and-serialization

public void ConfigureServices(IServiceCollection services)
{
...

services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );

...
}

#14


0  

Simply place Configuration.ProxyCreationEnabled = false; inside the context file; this will solve the problem.

简单的配置。ProxyCreationEnabled = false;在上下文文件;这将解决问题。

public demEntities()
    : base("name=demEntities")
{
    Configuration.ProxyCreationEnabled = false;
}

#15


-1  

For not looping this worked for me-
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,

对于没有循环的我来说这是可行的- ReferenceLoopHandling = referenceloophandling.忽略,

I've solved it all here - Entity Framework children serialization with .Net Core 2 WebAPI https://gist.github.com/Kaidanov/f9ad0d79238494432f32b8407942c606

我在这里已经解决了这一切-实体框架子序列化与。net Core 2 WebAPI https://gist.github.com/Kaidanov/f9ad0d79238494432f32b8407942c606

Will appreciate any remarks. maybe someone can use it sometime.

会欣赏任何言论。也许有人什么时候可以用它。

#16


-2  

I liked the solution that does it from Application_Start() as in the answer here

我喜欢Application_Start()中的解决方案,就像这里的答案一样

Apparently I could not access the json objects in JavaScript using the configuration within my function as in DalSoft's answer as the object returned had "\n \r" all over the (key, val) of the object.

显然,我不能使用函数中的配置访问JavaScript中的json对象,就像DalSoft的答案一样,因为返回的对象在对象的(key, val)上都有“\n \r”。

Anyway whatever works is great (because different approaches work in different scenario based on the comments and questions asked) though a standard way of doing it would be preferable with some good documentation supporting the approach.

不管怎样,任何有用的东西都很好(因为不同的方法在不同的场景中根据所询问的评论和问题进行工作),但是如果有一些好的文档支持这种方法,最好使用标准的方法。