分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

Json.NET如何避免循环引用

发布时间:2023-09-06 02:30责任编辑:苏小强关键词:.NET

Json.NET在将对象序列化为Json字符串的时候,如果对象有循环属性,那么会导致Json.NET抛出循环引用异常。

有两种方法可以解决这个问题:

1、在对象循环引用的属性上打上[JsonIgnore]标签,例如:

public class UserProfile{ ???public string UserCode { get; set; } ???public string UserName { get; set; } ???public string MailAddress { get; set; } ???public long LoginTimeStamp { get; set; } ???[JsonIgnore] ???protected List<Role> roles; ???[JsonIgnore] ???public List<Role> Roles ???{ ???????get ???????{ ???????????return roles; ???????} ???}}

2、另一个方法是在调用Json.NET的SerializeObject方法序列化对象时,设置ReferenceLoopHandling属性为ReferenceLoopHandling.Ignore,如下所示:

var stringObject = JsonConvert.SerializeObject(value, new JsonSerializerSettings(){ ???ReferenceLoopHandling = ReferenceLoopHandling.Ignore});

这样Json.NET检测到循环引用时,就会停止序列化操作,忽略对象的循环引用属性

Json.NET如何避免循环引用

原文地址:https://www.cnblogs.com/OpenCoder/p/10289667.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved