将实体框架对象序列化为 JSON

发布于 2024-12-10 07:22:12 字数 1694 浏览 0 评论 0原文

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)); 我收到以下错误:

序列化类型的对象时检测到循环引用 'System.Data.Metadata.Edm.AssociationType

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

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;
        }
    }
}

This works, but when i try with HttpContext.Current.Response.Write(serializer.Serialize(system)); i get the following error:

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

What i wanted was a json object representating the complete as_system object, so i dont have to map each property manually. Is there any way to solve this? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

羁绊已千年 2024-12-17 07:22:12

如果您想将实体框架对象序列化为 JSON,您可以使用 http://www.newtonsoft.com。为此,请从 nuget 安装 JSON.NET 并使用以下代码示例:

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

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

If you want Serialize Entity Framework Objects into JSON, You can use JSON.NET from http://www.newtonsoft.com. to do this, install JSON.NET from nuget and use following code sample:

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

ReferenceLoopHandling.Ignore can prevent circular reference error.

回心转意 2024-12-17 07:22:12

听起来 EF 并没有为您提供一个 ASSystem,而是提供了一些带有 EF goo 的微妙动态子类。如果这是正确的,我认为这里要做的最简单的事情就是使用类似 AutoMapper< /a> 获取非 EF 副本(进入 new ASSystem() 实例,不受 EF 影响)。但是,有一些替代方案:

  • 您可以尝试将 ASSystem 标记为 sealed,从而消除 EF 注入自身的能力
  • ,您编写自定义转换器和 注册它 - 不过,这可能比映射更多的工作

It sounds like EF is not giving you a ASSystem, but rather some subtle dynamic subclass of that with some EF goo. If that is correct, I would argue the simplest thing to do here is to use something like AutoMapper to get a non-EF copy (into a new ASSystem() instance, untouched by EF). However, a few alternatives:

  • you could try marking ASSystem as sealed, taking away EF's ability to inject itself
  • you you write a custom converter and register it - this is probably more work than mapping, though
别想她 2024-12-17 07:22:12

您可以创建一个 POCO 对象,该对象可以包含您的数据并且可以序列化。例如,定义:

public class MySystem {
  public int SID {get; set;}
  public string Description {get; set;}
  public string SystemName {get; set;}
}

在您的代码中使用以下语句:

IQuerable<MySystem> sysList = from s in ctx.AS_SYSTEM where s.SYSTEM_ID == query 
                           select new MySystem(){SID = s.SYSTEM_ID,  
                           Description = s.Description, SystemName = s.SystemName   };
MySystem sys = sysList.First();

现在您可以像示例中那样序列化 sys

You can create a POCO object that can contains your data and can be serialized. For example define:

public class MySystem {
  public int SID {get; set;}
  public string Description {get; set;}
  public string SystemName {get; set;}
}

in your code use this statement:

IQuerable<MySystem> sysList = from s in ctx.AS_SYSTEM where s.SYSTEM_ID == query 
                           select new MySystem(){SID = s.SYSTEM_ID,  
                           Description = s.Description, SystemName = s.SystemName   };
MySystem sys = sysList.First();

Now you can serialize sys as in your example.

流云如水 2024-12-17 07:22:12

不确定这是否有帮助,但尝试使用 DataContractJsonSerializer 而不是 JavaScriptSerializer。据我所知,DataContractJsonSerializer 优于 JavaScriptSerializer。

Not sure if this will help, but try to use DataContractJsonSerializer instead of JavaScriptSerializer. As far as I know DataContractJsonSerializer is prefered over JavaScriptSerializer.

旧时模样 2024-12-17 07:22:12

试试这个;它对我有用。

要返回 JSON 数据 [在 EF 中]:

  1. 将引用 System.Runtime.Serialization 添加到项目中。
  2. 编写如下代码:
using System.Web.Script.Serialization;

    public string getValuesJson()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        MyDBEntities ctx = new MyDBEntities();

        var myValues = (from m in ctx.TestEntity
                       where (m.id == 22)
                       select m).ToList();

        return js.Serialize(myValues);
    }

您还可以在 http://jsonlint.com/ 检查 JSON 字符串是否有效。

Try this; it works for me.

To return JSON data [in EF]:

  1. Add reference System.Runtime.Serialization to the project.
  2. Write code like below:
using System.Web.Script.Serialization;

    public string getValuesJson()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        MyDBEntities ctx = new MyDBEntities();

        var myValues = (from m in ctx.TestEntity
                       where (m.id == 22)
                       select m).ToList();

        return js.Serialize(myValues);
    }

You can also check whether JSON string is valid at http://jsonlint.com/.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文