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 メソッドを 2 回使用しています。必ずしもすべての値が必要なわけではないので、別の、より削減されたバージョンを作成する必要があります。 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 に答える