JSON Error: "A circular reference was detected while serializing an object of type ..."

Last post 07-30-2007 6:07 PM by Garbin. 7 replies.

Sort Posts:

  • JSON Error: "A circular reference was detected while serializing an object of type ..."

    07-26-2007, 5:55 PM
    • Loading...
    • kinger
    • Joined on 02-28-2003, 7:29 PM
    • Posts 87

    I'm trying to do pretty much exactly what this example (in the link shown below) shows. And I get the error of "A circular reference was detected...".

    http://ajax.asp.net/docs/tutorials/ConsumingWebServicesWithAJAXTutorial.aspx - Passing and Returning Complex Types - 2nd example

    Does anyone know why this error occurs?  Looking at the example (from the link), I would think that would generate the error, but it doesn't.

    Essentially what I'm trying to do is:

    In Javascript:

    • Collect form values from the HTML via Javascript
    • build an object of a specific type
    • set the properties
    • send the javascript object to a webservice method as an argument
    • then return the result from the webservice as a JSON object

    Here's my ASP.NET code:

     

    <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="jsontest.aspx.cs" Inherits="Products_jsontest" Title="JSON Test" %>
    <%@ Import Namespace="System.Web.Script.Serialization" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
        <asp:ScriptManager ID="scriptManager" runat="server">
            <Scripts>
                <asp:ScriptReference Path="~/scripts/handleproducts.js" />
            </Scripts>
            <Services>
                <asp:ServiceReference Path="~/ws/idcwebservice.asmx" />
            </Services>
        </asp:ScriptManager>
        <br />
        <asp:DropDownList ID="ddlColors" runat="server" onchange="getProductData(this);">
        </asp:DropDownList><br />
        <br />
        <div id="hdnProductID"></div>
        <div id="boxOptionsInnerBoxPricingTotalPrice"></div>
        <div id="boxOptionsInnerBoxPricingUnitPrice"></div>
        <div id="errorMsg"></div>
    </asp:Content>
     

    Here's my Javascript code:

    function getProductData(ctrl){
        var selectedIndex = ctrl.selectedIndex;
        var selectedColor = ctrl.options[selectedIndex].value;
        
        try{
            var prod = new IDCPrinting.ProductData();
            prod.ColorTypeID = selectedColor;
            prod.SizeTypeID = 1;
            prod.Quantity = 500;
            prod.CoatingTypeID = 1;
            prod.StockTypeID = 1;
            prod.Proof = false;
            prod.TurnaroundTypeID = 1;
            
            //alert(prod.Quantity);
            
            IDCPrinting.IDCPrintingWebService.GetProduct(prod, OnProductSucceededCallback, OnProductFailedCallback);
        }catch(e){
            alert("Error [getProductData]: " + e.message);
        }
    }
    
    // Callback function invoked on success
    function OnProductSucceededCallback(result, userContext, methodName){
        switch(methodName){
            case "GetProduct" :
            {
               var newObj = Sys.Serialization.JavaScriptSerializer.deserialize(result);
    
               var divHdnProductID = document.getElementById("hdnProductID");
               var divTotalPrice = document.getElementById("boxOptionsInnerBoxPricingTotalPrice");
               var divUnitPrice = document.getElementById("boxOptionsInnerBoxPricingUnitPrice");
    
               divHdnProductID.value = newObj.productID
               divUnitPrice.innerHTML = calcUnitPrice(newObj.price, quan);
               divTotalPrice.innerHTML = getProductTotal(newObj.price);
            break;
            }
        }
    }
    
    // Callback function invoked on failure 
    // of the Web service methods. 
    function OnProductFailedCallback(error, userContext, methodName) 
    {
      if(error !== null) 
      {
       var divError = document.getElementById("errorMsg");
          divError.innerHTML = "An error occurred: " + error.get_message();
      }
    }
    
    
    if(typeof('Sys') !== 'undefined') Sys.Application.notifyScriptLoaded();

     

    Here's my webservice code:

    using System;
    using System.Web;
    using System.Collections;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.Web.Script.Services;
    using System.Web.Script.Serialization;
    using System.Collections.Generic;
    using IDC.BusinessObjects;
    
    namespace IDC
    {
    
        #region ProductData class
    
        public class ProductData
        {
            public ProductData()
            {
    
            }
    
            private int _ColorTypeID;
    
            public int ColorTypeID
            {
                get { return _ColorTypeID; }
                set { _ColorTypeID = value; }
            }
    
            private int _SizeTypeID;
    
            public int SizeTypeID
            {
                get { return _SizeTypeID; }
                set { _SizeTypeID = value; }
            }
    
            private int _Quantity;
    
            public int Quantity
            {
                get { return _Quantity; }
                set { _Quantity = value; }
            }
    
            private int _CoatingTypeID;
    
            public int CoatingTypeID
            {
                get { return _CoatingTypeID; }
                set { _CoatingTypeID = value; }
            }
    
            private int _StockTypeID;
    
            public int StockTypeID
            {
                get { return _StockTypeID; }
                set { _StockTypeID = value; }
            }
    
            private bool _Proof;
    
            public bool Proof
            {
                get { return _Proof; }
                set { _Proof = value; }
            }
    
            private int _TurnaroundTypeID;
    
            public int TurnaroundTypeID
            {
                get { return _TurnaroundTypeID; }
                set { _TurnaroundTypeID = value; }
            }
    
            private int _AddressingTypeID;
    
            public int AddressingTypeID
            {
                get { return _AddressingTypeID; }
                set { _AddressingTypeID = value; }
            }
    
            private int _BindingFinishingTypeID;
    
            public int BindingFinishingTypeID
            {
                get { return _BindingFinishingTypeID; }
                set { _BindingFinishingTypeID = value; }
            }
    
            private int _CardSlotTypeID;
    
            public int CardSlotTypeID
            {
                get { return _CardSlotTypeID; }
                set { _CardSlotTypeID = value; }
            }
    
            private int _CoverPagesTypeID;
    
            public int CoverPagesTypeID
            {
                get { return _CoverPagesTypeID; }
                set { _CoverPagesTypeID = value; }
            }
    
            private int _FoldingTypeID;
    
            public int FoldingTypeID
            {
                get { return _FoldingTypeID; }
                set { _FoldingTypeID = value; }
            }
    
            private int _InsidePagesTypeID;
    
            public int InsidePagesTypeID
            {
                get { return _InsidePagesTypeID; }
                set { _InsidePagesTypeID = value; }
            }
    
            private int _NumberOfMonthsTypeID;
    
            public int NumberOfMonthsTypeID
            {
                get { return _NumberOfMonthsTypeID; }
                set { _NumberOfMonthsTypeID = value; }
            }
    
            private int _PagingTypeID;
    
            public int PagingTypeID
            {
                get { return _PagingTypeID; }
                set { _PagingTypeID = value; }
            }
    
            private int _SecondSheetTypeID;
    
            public int SecondSheetTypeID
            {
                get { return _SecondSheetTypeID; }
                set { _SecondSheetTypeID = value; }
            }
    
            private bool _Perforation;
    
            public bool Perforation
            {
                get { return _Perforation; }
                set { _Perforation = value; }
            }
    
            private bool _Scoring;
    
            public bool Scoring
            {
                get { return _Scoring; }
                set { _Scoring = value; }
            }
    
            private bool _Tabbing;
    
            public bool Tabbing
            {
                get { return _Tabbing; }
                set { _Tabbing = value; }
            }
    
    
        }
    
    
        #endregion
    
        /// <summary>
        /// Summary description for IDCWebService
        /// </summary>
        [WebService(Namespace = "http://idc.com/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [GenerateScriptType(typeof(ProductData))]
        [ScriptService]
        public class IDCWebService : System.Web.Services.WebService
        {
    
            public IDCWebService()
            {
    
                //Uncomment the following line if using designed components 
                //InitializeComponent(); 
            }
    
            [WebMethod]
            public object GetProduct(ProductData prod)
            {
                Products p = new Products();
                p.Query.Where(
                    p.Query.ColorTypeID.Equal(prod.ColorTypeID),
                    p.Query.SizeTypeID.Equal(prod.SizeTypeID),
                    p.Query.Quantity.Equal(prod.Quantity),
                    p.Query.CoatingTypeID.Equal(prod.CoatingTypeID),
                    p.Query.StockTypeID.Equal(prod.StockTypeID),
                    p.Query.Proof.Equal(prod.Proof),
                    p.Query.TurnaroundTypeID.Equal(prod.TurnaroundTypeID));
                p.Query.Load();
    
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                return serializer.Serialize(p);
                //return p;
            }
    
        }
    }
    

     

    Any help would be appreciated.

    Thanks.

  • Re: JSON Error: "A circular reference was detected while serializing an object of type ..."

    07-27-2007, 2:47 AM
    • Loading...
    • Garbin
    • Joined on 09-17-2004, 8:35 AM
    • Sassari, Italy
    • Posts 1,494
    • ASPInsiders
      TrustedFriends-MVPs

    Hi,

    could you show the declaration for Products?

    Also, there's no need to serialize an object in the web method. You can simply set Products as the method return type and return an instance. The instance will be automatically serialized.
     

    Alessandro Gallo | Blog | My book: ASP.NET AJAX In Action
  • Re: JSON Error: "A circular reference was detected while serializing an object of type ..."

    07-27-2007, 1:22 PM
    • Loading...
    • kinger
    • Joined on 02-28-2003, 7:29 PM
    • Posts 87

    Actually it would be quite large because it's generated by the ORM tool Entity Spaces (http://www.entityspaces.net).  It's based on my Products table.

    Also, another reason that this bothers and confuses me, is that this works if I use Jayrock JSON component (http://jayrock.berlios.de/) where it's doing the exact same thing.  I just wanted to see if it would work with ASP.NET AJAX (JSON) and at the moment it doesn't.  I'm sure that it does work, but I'm obviously missing something to make this work.

    Also, there's no need to serialize an object in the web method. You can simply set Products as the method return type and return an instance. The instance will be automatically serialized.

    I tried that just returning "p" and I got the same error so I thought I would try the Serializing.

  • Re: JSON Error: "A circular reference was detected while serializing an object of type ..."

    07-27-2007, 5:59 PM
    • Loading...
    • dwahlin
    • Joined on 06-14-2002, 7:09 PM
    • Arizona
    • Posts 18
    • TrustedFriends-MVPs

    I haven't seen this in my projects but came across the following which may be useful since your object code is being generated: 

    http://sqljunkies.com/WebLog/kmarple/archive/2005/01/11/6180.aspx

    It may have nothing to do with the issue but I thought I'd pass it along.

    Dan
    Filed under:
  • Re: JSON Error: "A circular reference was detected while serializing an object of type ..."

    07-27-2007, 6:15 PM
    • Loading...
    • kinger
    • Joined on 02-28-2003, 7:29 PM
    • Posts 87

    Dan,

    Thanks for the response.  Yeah, I looked at this post a few days ago.  It doesn't seem like it can be applied to my issue, but I did look it over.

    My frustration comes from the ASP.NET example on passing JSON objects, and I'm doing exactly what this example is doing, yet I get a circular reference error.  And why I get this error with ASP.NET AJAX and not when I use Jayrock, compounds my confusion.  Tongue Tied

    One thought though, I did read something somewhere (I forget where) that suggested that some circular references might occur in pages used with Master Pages.  Could this be a reason?

    Thanks,

    King

    Filed under: ,
  • Re: JSON Error: "A circular reference was detected while serializing an object of type ..."

    07-29-2007, 7:02 PM

    I think the Problem must be with the EntitySpace and I guess the Product is an inherited class from any EntitySpace object, which I think got something that is not compatible with the default serialization of JavaScriptSerializer In that I would suggest to write some custom convertors. May be you can check the DataTable, DataSet convertors to see how it is done.

    Long Live .NET
    Kazi Manzur Rashid (Amit)
    _________________________
    http://weblogs.asp.net/rashid/
  • Re: JSON Error: "A circular reference was detected while serializing an object of type ..."

    07-30-2007, 1:32 AM
    • Loading...
    • kinger
    • Joined on 02-28-2003, 7:29 PM
    • Posts 87

    I would almost agree with you that the problem lies within Entity Spaces, but this exact code works fine using Jayrock.  I was just hoping I could use ASP.NET AJAX to transmit JSON objects back and forth.

    Filed under: ,
  • Re: JSON Error: "A circular reference was detected while serializing an object of type ..."

    07-30-2007, 6:07 PM
    • Loading...
    • Garbin
    • Joined on 09-17-2004, 8:35 AM
    • Sassari, Italy
    • Posts 1,494
    • ASPInsiders
      TrustedFriends-MVPs

    Hi,

    it depends on the kind of JSON serializer/deserializer that Jayrocks implements. The one implemented by ASP.NET AJAX doesn't handle circular references, simply because they can't be expressed in JSON syntax.

    Probably Jayrocks implements one of the many JSON variants, such as JSPON.
     

    Alessandro Gallo | Blog | My book: ASP.NET AJAX In Action
Page 1 of 1 (8 items)
Microsoft Communities
Page view counter