chu*_*nce 20 c# asp.net asp.net-mvc json json.net
我的项目中有一个带有循环引用的对象.我把[JsonIgnore]放在字段上面就像这样:
[JsonIgnore]
public virtual Foobar ChildObject { get; set; }
Run Code Online (Sandbox Code Playgroud)
当我序列化对象时,我仍然得到循环引用错误.唯一没有JsonIgnore的字段是字符串字段,不应该导致这种情况.为了让JsonIgnore工作,我还需要做些什么吗?
谢谢!
Jus*_*lle 26
您可能还有一些其他属性链接回其父级.使用此ReferenceLoopHandling.Ignore设置可防止自引用循环.
using Newtonsoft.Json;
JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
string json = JsonConvert.SerializeObject(foobars, Formatting.None, jsSettings);
Run Code Online (Sandbox Code Playgroud)
use*_*142 26
我错误地解析了 JsonIgnore 参考。
请注意,此属性存在于多个命名空间中:
我已经在 VS 中解决了System.Text.Json.Serialization.JsonIgnore - 但是我使用 Newtonsoft 库进行我的实际序列化/反序列化 - 因此该属性被忽略。更改对Newtonsoft.Json.JsonIgnore的引用已解决。