gpt4 book ai didi

c# - 序列化对象时检测到循环引用 - C#、Json

转载 作者:行者123 更新时间:2023-11-30 22:28:53 63 4
gpt4 key购买 nike

我正在尝试序列化一个对象以以 Json 格式返回它以创建一个图形。我在类库中执行此操作并将字符串作为更大报告的一部分返回。我收到一条错误消息:

序列化“MyApp.Data.Shop”类型的对象时检测到循环引用

我正在学习本教程并期望返回类似的 Json 字符串(当然有更多字段)- Tutorial

我的报告引擎中的这个方法抛出错误 -

public string GetMonthlyShopSalesJson(List<Sale> sales, MonthlyRequest reportRequest)
{
List<MonthlyShopSales> mrs = GetMonthlyShopSales(sales, reportRequest);

JavaScriptSerializer serializer = new JavaScriptSerializer();
string jsonData = serializer.Serialize(mrs); //Error line

return jsonData;
}

这是我检索 shopsales 的方法:

public List<MonthlyShopSales> GetMonthlyShopSales(List<Sale> sales, MonthlyRequest reportRequest)
{
ModelContainer ctn = new ModelContainer();
MonthlyDateRange dates = GetComparativeDateRange(reportRequest);

List<MonthlyShopSales> shopSales = (from sale in sales
orderby sale.Shop.Name
group sale by sale.Shop into ret
select new MonthlyShopSales
{
Shop = ret.Key,
TotalNumItemsSoldUSD = ret.Where(it => it.USDCut.HasValue).Where(it => it.USDCut != 0).Count(),
TotalNumItemsSoldGBP = ret.Where(it => it.GBPCut.HasValue).Where(it => it.GBPCut != 0).Count(),
TotalNumItemsSoldEUR = ret.Where(it => it.EURCut.HasValue).Where(it => it.EURCut != 0).Count(),
USDTotalEarnings = PerformCurrencyConversion(ret.Sum(it => it.USDCut.HasValue ? it.USDCut.Value : 0), 0M, 0M, reportRequest.Currency, dates.BaseStartDate),
GBPTotalEarnings = PerformCurrencyConversion(0M, ret.Sum(it => it.GBPCut.HasValue ? it.GBPCut.Value : 0), 0M, reportRequest.Currency, dates.BaseStartDate),
EURTotalEarnings = PerformCurrencyConversion(0M, 0M, ret.Sum(it => it.EURCut.HasValue ? it.EURCut.Value : 0), reportRequest.Currency, dates.BaseStartDate),
TotalNumItemsSoldUSDOverall = sales.Where(it => it.USDCut.HasValue).Where(it => it.USDCut != 0).Count(),
TotalNumItemsSoldGBPOverall = sales.Where(it => it.GBPCut.HasValue).Where(it => it.GBPCut != 0).Count(),
TotalNumItemsSoldEUROverall = sales.Where(it => it.EURCut.HasValue).Where(it => it.EURCut != 0).Count(),
USDTotalEarningsOverall = PerformCurrencyConversion(sales.Sum(it => it.USDCut.HasValue ? it.USDCut.Value : 0), 0M, 0M, reportRequest.Currency, dates.BaseStartDate),
GBPTotalEarningsOverall = PerformCurrencyConversion(0M, sales.Sum(it => it.GBPCut.HasValue ? it.GBPCut.Value : 0), 0M, reportRequest.Currency, dates.BaseStartDate),
EURTotalEarningsOverall = PerformCurrencyConversion(0M, 0M, sales.Sum(it => it.EURCut.HasValue ? it.EURCut.Value : 0), reportRequest.Currency, dates.BaseStartDate)
}).ToList();
return shopSales;
}

然后这是我的 MonthlyShopSales 类(class):

public class MonthlyShopSales
{
public Shop Shop { get; set; }

public int TotalNumItemsSoldUSD { get; set; }
public int TotalNumItemsSoldGBP { get; set; }
public int TotalNumItemsSoldEUR { get; set; }
public int NumberOfItemsSoldPerShop { get { return TotalNumItemsSoldUSD + TotalNumItemsSoldGBP + TotalNumItemsSoldEUR; } }

public decimal USDTotalEarnings { get; set; }
public decimal GBPTotalEarnings { get; set; }
public decimal EURTotalEarnings { get; set; }

public decimal OverallEarningsPerShop { get { return USDTotalEarnings + GBPTotalEarnings + EURTotalEarnings; } }

public decimal QtyPercentageOfSales { get { return ((decimal)NumberOfItemsSoldPerShop / (decimal)TotalNumberOfBooksSoldOverall) * 100; } }
public decimal RevenuePercentageOfSales { get { return (OverallEarningsPerShop / TotalEarningsOverall) * 100; } }

public int TotalNumItemsSoldUSDOverall { get; set; }
public int TotalNumItemsSoldGBPOverall { get; set; }
public int TotalNumItemsSoldEUROverall { get; set; }
public int TotalNumberOfItemsSoldOverall { get { return TotalNumItemsSoldUSDOverall + TotalNumItemsSoldGBPOverall + TotalNumItemsSoldEUROverall; } }

public decimal USDTotalEarningsOverall { get; set; }
public decimal GBPTotalEarningsOverall { get; set; }
public decimal EURTotalEarningsOverall { get; set; }

public decimal TotalEarningsOverall { get { return USDTotalEarningsOverall + GBPTotalEarningsOverall + EURTotalEarningsOverall; } }
}

我正在努力使我正在编写的代码相对高效,这就是我两次使用 GetMonthlyShopSales 方法的原因 - 我不一定需要它的所有值,所以我应该编写一个单独的、更精简的代码我的 Json 字符串的版本?我也不确定这是否是我的问题,所以如果有人可以提供帮助,那就太好了。

这里是任何擅长阅读的人的堆栈跟踪:

[InvalidOperationException: A circular reference was detected while serializing an object of type 'MyApp.Data.Shop'.]
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1549
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +502
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1424
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +126
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1380
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +502
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1424
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +502
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1424
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +126
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +1380
System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +194
System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat) +26
System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat) +74
System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj) +6
MyApp.Business.Reporting.AdvancedReportingEngine.GetMonthlyShopSalesJson(List`1 sales, MonthlyRequest reportRequest) in C:\Development\MyApp\MyApp.Business\Reporting\AdvancedReportingEngine.cs:75
MyApp.Business.Reporting.AdvancedReportingEngine.GetMonthlyReport(MonthlyRequest reportRequest) in C:\Development\MyApp\MyApp.Business\Reporting\AdvancedReportingEngine.cs:61
MyApp.Web.Areas.User.Controllers.ReportsController.MonthlyDashboardReport(MonthlyRequest reportRequest, FormCollection formValues) in C:\Development\MyApp\MyApp.Web\Areas\User\Controllers\ReportsController.cs:34
lambda_method(Closure , ControllerBase , Object[] ) +157
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

编辑:

根据要求,这是商店类。它源自 EF 数据模型,但无论如何只有 3/4 字段:

[MetadataType(typeof(ShopMetadata))]
public partial class Shop
{

}

public partial class ShopMetadata
{
[DisplayName("Shop Name")]
[Required(ErrorMessage = "You must specify a Shop name")]
public string Name { get; set; }

[DisplayName("Region")]
[Required(ErrorMessage = "You must specify a region")]
public int Region { get; set; }

[DisplayName("Display Sequence")]
[Required(ErrorMessage = "You must specify a dispay sequence")]
public int DisplaySequence { get; set; }
}

最佳答案

我怀疑问题出在 Shop EF POCO 类上。 Entity Framework 在幕后添加了很多其他东西。因此,即使您的商店类我只有 3/4 属性,但在引擎盖下它可能有更多。见:

Entity framework serialize POCO to JSON

有些人建议使用 Json.NET,或者您可以使用商店 DTO 类,并将 MonthlyShopSales 中的商店对象替换为 DTO 版本。

关于c# - 序列化对象时检测到循环引用 - C#、Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10532196/

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