Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Circular reference exception while Serializing DataTable object in .Net

    • 0
    • 0
    • 0
    • 2
    • 0
    • 0
    • 0
    • 2.81k
    Answer it

    How to serialize DataTable object in .Net

    Hi, While working in a .Net project, I am facing an Exception while serializing DataTable object using JavaScriptSerializer. The Exception I am getting is "A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'".

    The code, I have written is as follows:-

     public string SetData()
      {
         DataTable dt = new DataTable();
         dt.Columns.Add("id");
         dt.Columns.Add("Name");
    
         dt.Rows.Add("1", "Manish");
         dt.Rows.Add("2", "Ajay");
         dt.Rows.Add("3", "Ravi");
         dt.Rows.Add("4", "Rahul");
    
         JavaScriptSerializer serial = new JavaScriptSerializer();
         string x = serial.Serialize(dt);
    
         return x;
      }
    

    The following image will give the clear idea this Exception:

    alt text

    If anyone has any idea why I am getting this Exception of Circular Reference and how can I resolve it ?

    Thanks in advance..!

 2 Answer(s)

  • Hi Mayank,
    A circular reference is something like following:-
    root>child>parent>child>root...
    Because when serialization is done(in XML or json), the serialized data follows the node(XML) or key value(json) structure. If your object(to be serialized) is not structured properly,that may result to a circular reference.
    Now,the answer of the question in your case is to tell the compiler to avoid it by using following code

    JsonConvert.SerializeObject(myObject, Formatting.Indented, 
                                new JsonSerializerSettings { 
                                       ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
                                })
    

    This code simply tells the compiler to ignore the above described loop of circular reference and move on with the actual job which is the serialization of the provided object.

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: