简体   繁体   English

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

[英]Serializing Entity Framework Objects into 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)); 这工作,但当我尝试使用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 序列化“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. 我想要的是一个json对象代表完整的as_system对象,所以我不必手动映射每个属性。 Is there any way to solve this? 有什么方法可以解决这个问题吗? Thanks! 谢谢!

If you want Serialize Entity Framework Objects into JSON, You can use JSON.NET from http://www.newtonsoft.com . 如果您希望将实体框架对象序列化为JSON,则可以使用http://www.newtonsoft.com上的 JSON.NET。 to do this, install JSON.NET from nuget and use following code sample: 为此,从nuget安装JSON.NET并使用以下代码示例:

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

ReferenceLoopHandling.Ignore can prevent circular reference error. ReferenceLoopHandling.Ignore可以防止循环引用错误。

It sounds like EF is not giving you a ASSystem , but rather some subtle dynamic subclass of that with some EF goo. 听起来EF并没有给你一个ASSystem ,而是一些微妙的动态子类,带有一些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). 如果这是正确的,我认为这里最简单的方法使用类似AutoMapper的东西来获取非EF副本(进入new ASSystem()实例,不受EF影响)。 However, a few alternatives: 但是,有几种选择:

  • you could try marking ASSystem as sealed , taking away EF's ability to inject itself 您可以尝试将ASSystem标记为sealed ,从而消除EF注入自身的能力
  • you you write a custom converter and register it - this is probably more work than mapping, though 你编写一个自定义转换器并注册它 - 这可能比映射更多的工作

You can create a POCO object that can contains your data and can be serialized. 您可以创建一个POCO对象,该对象可以包含您的数据并且可以序列化。 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. 现在,您可以在示例中序列化sys

Try this; 尝试这个; it works for me. 这个对我有用。

To return JSON data [in EF]: 要返回[在EF中]的JSON数据:

  1. Add reference System.Runtime.Serialization to the project. 将参考System.Runtime.Serialization添加到项目中。
  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/ . 您还可以在http://jsonlint.com/上检查JSON字符串是否有效。

Not sure if this will help, but try to use DataContractJsonSerializer instead of JavaScriptSerializer. 不确定这是否有帮助,但尝试使用DataContractJsonSerializer而不是JavaScriptSerializer。 As far as I know DataContractJsonSerializer is prefered over JavaScriptSerializer. 据我所知,DataContractJsonSerializer优先于JavaScriptSerializer。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM