问题
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