C# Newtonsoft.json 中的 ReferenceLoopHandling.Ignore 究竟是做什么的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11979637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:55:54  来源:igfitidea点击:

What does ReferenceLoopHandling.Ignore in Newtonsoft.json exactly do?

c#.netjsonjson.net

提问by DotNetInfo

Can anyone present me a scenario where it can be used. What I understand by ReferenceLoopHandling.Ignoreis if you have an object A which references object B and B references C and C again references A (A->B->C->A), then when serializing, it will end up in endless loop between C and A, which can be avoided using below. Am I right?

任何人都可以向我展示一个可以使用它的场景。我对ReferenceLoopHandling.Ignore 的理解是,如果你有一个对象 A 引用对象 B 和 B 引用 C 并且 C 再次引用 A (A->B->C->A),那么在序列化时,它将以无休止的方式结束C 和 A 之间的循环,可以避免使用下面的循环。我对吗?

 JsonConvert.SerializeObject(data, 
     Formatting.Indented, 
     new JsonSerializerSetting()
         {
             ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
         } 
 ));

I am having self referencing loop issue which gets solved by using the above, but I want to understand exactly what it is doing as the above line is the meat of the application (critical meat)

我有自引用循环问题,可以通过使用上面的方法解决,但我想确切地了解它在做什么,因为上面的行是应用程序的主要内容(关键内容)

回答by DuckMaestro

The documentation on this is available here: http://james.newtonking.com/projects/json/help/html/SerializationSettings.htm

关于此的文档可在此处获得:http: //james.newtonking.com/projects/json/help/html/SerializationSettings.htm

As of this writing, the behavior is described there as follows (with emphasis mine):

在撰写本文时,行为描述如下(重点是我的):

ReferenceLoopHandling.Error: By default Json.NET will error if a reference loop is encountered (otherwise the serializer will get into an infinite loop).

ReferenceLoopHandling.Ignore: Json.NET will ignore objects in reference loops and not serialize them. The first time an object is encountered it will be serialized as usual but if the object is encountered as a child object of itself the serializer will skip serializing it.

ReferenceLoopHandling.Serialize: This option forces Json.NET to serialize objects in reference loops. This is useful if objects are nested but not indefinitely.

ReferenceLoopHandling.Error: 默认情况下,如果遇到引用循环,Json.NET 将出错(否则序列化程序将进入无限循环)。

ReferenceLoopHandling.Ignore:Json.NET 将忽略引用循环中的对象并且不会序列化它们。第一次遇到对象时,它会像往常一样被序列化,但如果该对象是作为其自身的子对象遇到的,则序列化程序将跳过对其进行序列化。

ReferenceLoopHandling.Serialize:此选项强制 Json.NET 序列化引用循环中的对象。如果对象是嵌套的但不是无限期的,这很有用。