[ScriptIgnore] 属性在正在序列化的直接对象上对我来说效果很好,但是如果我将它放在相关对象的属性上(从直接对象上的属性引用),它就不起作用申请吗?
即 Json(用户)
IE
class user {
Badges badges
}
class Badge {
[ScriptIgnore]
SomeObject obj; //Causes circular reference error because scriptignore doesn't apply
}
有办法解决这个问题吗?
最佳答案
Is there a way to get around this?
我建议您使用仅公开所需属性的 View 模型,并将 View 模型传递给 Json 方法。
如果您不想遵循我推荐的 View 模型方法,那么 [ScriptIgnore]
属性也应该适合您。
示例:
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class User
{
public IEnumerable<Badge> Badges { get; set; }
}
public class Badge
{
[ScriptIgnore]
public User User { get; set; }
}
public class Program
{
static void Main()
{
var user = new User();
var badge = new Badge { User = user };
user.Badges = new[] { badge };
var serializer = new JavaScriptSerializer();
Console.WriteLine(serializer.Serialize(user));
}
}
如果从 Badge
类的 User
属性中删除 [ScriptIgnore]
属性,JSON 序列化将因循环引用错误而失败。
关于ASP.NET [ScriptIgnore] 不适用于相关对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12023048/