c# - 将 Entity Framework 对象序列化为 JSON

标签 c# javascript json entity-framework

public class GenericHandler : IHttpHandler
{
    public class ASSystem
    {
        public string SID { get; set; }
        public string Description { get; set; }
        public string SystemName { get; set; }
    }

    public class ErrorObj
    {
        public string ErrorMessage { get; set; }
    }

    public void ProcessRequest(HttpContext context)
    {
        HttpContext.Current.Response.ContentType = "application/json";
        HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;

        string query = HttpContext.Current.Request.QueryString["SID"];


        SOFAEntities ctx = new SOFAEntities();
        JavaScriptSerializer serializer = new JavaScriptSerializer();

        try
        {
            AS_SYSTEM system = ctx.AS_SYSTEM.Where(s => s.SYSTEM_ID == query).First() as AS_SYSTEM;

            if (system != null)
            {
                ASSystem sys = new ASSystem() { SID = system.SYSTEM_ID, Description = system.DESCRIPTION, SystemName = system.SYSTEM_NAME };
                HttpContext.Current.Response.Write(serializer.Serialize(sys));
            }
        }
        catch (Exception e)
        {
            HttpContext.Current.Response.Write(serializer.Serialize(new ErrorObj() { ErrorMessage = e.Message }));
        }





    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

这有效,但是当我尝试使用 HttpContext.Current.Response.Write(serializer.Serialize(system)); 时,我收到以下错误:

A circular reference was detected while serializing an object of type 'System.Data.Metadata.Edm.AssociationType

我想要的是一个表示完整 as_system 对象的 json 对象,因此我不必手动映射每个属性。有什么办法可以解决这个问题吗?谢谢!

最佳答案

如果您想将 Entity Framework 对象序列化为 JSON,您可以使用来自 http://www.newtonsoft.com 的 JSON.NET .为此,从 nuget 安装 JSON.NET 并使用以下代码示例:

return Newtonsoft.Json.JsonConvert.SerializeObject(results, Formatting.Indented, 
new JsonSerializerSettings { 
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
});

ReferenceLoopHandling.Ignore 可以防止循环引用错误。

关于c# - 将 Entity Framework 对象序列化为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7790890/

相关文章:

c# - 如何禁用向上/向下键滚动 Visual Studio 中的方法重载?

javascript - 用于解析工作时间字符串的正则表达式模式

javascript - jQuery 点击两次内运行函数

php - 从 PHP 获取数组值到 javascript

javascript - Angular 2 : SyntaxError: JSON. 解析:JSON 数据第 1 行第 1 列出现意外字符

javascript - 我现在有一个 json 对象,如何使用元素制作 div

c# - 如何动态填充 TreeView (C#)

C#选择列表中的元素作为字符串列表

c# - 如何在 C#/XAML windows 8 应用程序中预选多个 ListView / GridView 项目?

javascript - 在 jQuery 中使用 JSON 变量来显示更多 JSON 变量