Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

c# - What does ReferenceLoopHandling.Ignore in Newtonsoft.json exactly do?

Can anyone present me a scenario where it can be used. What I understand by ReferenceLoopHandling.Ignore is 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?

 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The documentation on this is available here: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...