2

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?

Community
  • 1
  • 1
dumbledad
  • 16,305
  • 23
  • 120
  • 273
  • You might have a look at my answer on **[“Self Referencing Loop Detected” exception with JSON.Net](https://stackoverflow.com/questions/40472419/self-referencing-loop-detected-exception-with-json-net/51235783#51235783)** page. – Murat Yıldız Jul 08 '18 at 20:40

1 Answers1

3

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).

Community
  • 1
  • 1
dumbledad
  • 16,305
  • 23
  • 120
  • 273