代码之家  ›  专栏  ›  技术社区  ›  thalm

如何使用newtonsoft.json为特定类型设置ObjectCreationHandling?

  •  0
  • thalm  · 技术社区  · 7 年前

    我有自引用数据:每个项目都包含它所属的剪贴簿列表,每个剪贴簿都包含它所包含的项目列表。很明显这是循环的,所以当一个剪贴簿被序列化时,我会得到一个newtonsoft.json.jsonserializationException“self-referenceloop detected”错误。我们在我们的Azure移动服务服务器上通过添加

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

    App_Start() 方法 Global.asax.cs 文件。但是在电话客户机中,我在这行代码处得到了例外:

    await _ScrapbookTable.UpdateAsync(liveScrapbook); 
    

    其中“剪贴簿”类型为 Microsoft.WindowsAzure.Services.MobileServices.IMobileServiceTable<Scrapbook> .

    The documentation (和) other answers here )演示如何修复此问题:

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

    但是这个修复程序假定是我的代码在进行序列化,而不是在对API函数的调用中(在我的例子中 Microsoft.WindowsAzure.Services.MobileServices.IMobileServiceTable<Scrapbook>.UpdateAsync )

    有没有一种方法可以用JSON属性(例如 [JsonObject(MemberSerialization.OptIn)] )为了防止例外?

    0 回复  |  直到 7 年前
        1
  •  3
  •   Community Mohan Dere    9 年前

    看起来我要做的就是 IsReference attribute 到我的项目类:

    [JsonObject(IsReference = true)]
    public class Item
    

    (如中的Fix 3所示 Boshoy's answer 类似的问题)。