本文介绍了Newtonsoft.Json.JsonSerializationException“检测到自引用循环"在库代码中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有自引用数据:每个项目都包含一个剪贴簿列表,它是该剪贴簿的成员,每个剪贴簿都包含一个包含列表的项目列表.显然,这是循环的,因此当对Scrapbook进行序列化时,我收到Newtonsoft.Json.JsonSerializationException检测到自引用循环"错误.通过添加该行,我们可以在Azure移动服务服务器上解决此问题

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;

Global.asax.cs文件的App_Start()方法中的

.但是在电话客户端中,我在这行代码中遇到了异常:

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

_ScrapbookTable的类型为Microsoft.WindowsAzure.Services.MobileServices.IMobileServiceTable<Scrapbook>.

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 });

但是此修复程序假定是我的代码在进行序列化,而不是在对API函数的调用之内(在我的情况下 Microsoft.WindowsAzure.Services.MobileServices.IMobileServiceTable<Scrapbook>.UpdateAsync ).

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

有没有一种方法可以用Json属性装饰Item和Scrapbook类(例如 [JsonObject(MemberSerialization.OptIn)] )以防止出现异常?

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

推荐答案

看来我需要做的就是添加我的Item类的IsReference属性:

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

[JsonObject(IsReference = true)]
public class Item

(如 Boshoy对类似问题的回答中的修订3所述.)

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

这篇关于Newtonsoft.Json.JsonSerializationException“检测到自引用循环"在库代码中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 18:23