gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:04:43 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com