Newtonsoft.Json.JsonSerializationException “Self referencing loop detected” in library code

不羁岁月 提交于 2019-12-31 03:26:28

问题


I have self referencing data: each Item contains a list of Scrapbooks that it is a member of and each Scrapbook contains a list of Items it contains. Clearly that's circular, and so when a Scrapbook is serialised I get a Newtonsoft.Json.JsonSerializationException "Self referencing loop detected" error. We get around this on our Azure Mobile Services server by adding the line

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;

in the App_Start() method of the Global.asax.cs file. But in the phone client I get the exception at this line of code:

await _ScrapbookTable.UpdateAsync(liveScrapbook); 

where _ScrapbookTable is of type Microsoft.WindowsAzure.Services.MobileServices.IMobileServiceTable<Scrapbook>.

The documentation (and other answers here) show how to fix this:

var json = JsonConvert.SerializeObject(joe, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

But this fix assumes that it is my code doing the serializing, rather than it being inside a call to an API function (in my case Microsoft.WindowsAzure.Services.MobileServices.IMobileServiceTable<Scrapbook>.UpdateAsync).

Is there a way I could decorate the Item and Scrapbook classes with Json attributes (e.g. [JsonObject(MemberSerialization.OptIn)]) to prevent the exception?


回答1:


It looks like all I need to do is add the IsReference attribute to my Item class:

[JsonObject(IsReference = true)]
public class Item

(as suggested as Fix 3 in Boshoy's answer to a similar question).



来源:https://stackoverflow.com/questions/32274539/newtonsoft-json-jsonserializationexception-self-referencing-loop-detected-in-l

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!