2

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

A circular reference was detected while serializing an object of type 'MyApp.Data.Shop'.

我正在关注本教程并期望返回一个类似的 Json 字符串(当然还有更多字段) -教程

在我的报告引擎中,此方法中引发了错误-

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

这是我检索商店销售额的方法:

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 课程:

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

2 回答 2

3

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

实体框架将 POCO 序列化为 JSON

有人建议使用 Json.NET,也可以使用 shop DTO 类,将 MonthlyShopSales 中的 Shop 对象替换为 DTO 版本。

于 2012-05-10T11:07:31.477 回答
0

看看这里,它可能会有所帮助。

另一方面,我处理过 Microsoft 反序列化器和 json.net。我认为 json.net 是一种更有效、更快的方式。还有 fastjson 库。

于 2012-05-10T10:49:37.757 回答