locked
JSON serialise issue RRS feed

  • Question

  • I converted entity frmaework to POCO and the resulted classes school , and document looks like

     [DataContract] 
    public school
    {
     [DataMember] public Nullable<int> DocumentId { get; set; }
     [DataMember]public virtual Document Document { get; set; }
    }
    
     [DataContract] 
    public Document
    {
     [DataMember] public int Id { get; set; }
            [DataMember] public string ShortString { get; set; }
    [DataMember] public virtual ICollection<school> Nouns { get; set; }
    
    }
    

    I got successfully schools.Include("Document")

    if I tried to serialise the resulted list of above using method like 

    public static string Serialize<T>(T data)
                {
                    try
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            var serializer = new DataContractJsonSerializer(typeof(T));
                            serializer.WriteObject(memoryStream, data);
    
                            memoryStream.Seek(0, SeekOrigin.Begin);
    
                            var reader = new StreamReader(memoryStream);
                            string content = reader.ReadToEnd();
                            return content;
                        }
                    }
                    catch (System.Exception)
                    {
    
                        return string.Empty;
                    }
                }

    I get error 

    Object graph for type 'School' contains cycles and cannot be serialized if reference tracking is disabled.

    I cannot solve that by add, becuase it's json serialsing and will raise another error

     [DataContract IsReference="true"] 


    Thursday, May 15, 2014 9:07 PM

Answers

  • Hi, "cycles" means school class refers to Document class and Document class also refes to school class:

    public school
    {
     [DataMember] public Nullable<int> DocumentId { get; set; }
     [DataMember]public virtual Document Document { get; set; }//document class in school class
    }
    public Document
    {
     [DataMember] public int Id { get; set; }
            [DataMember] public string ShortString { get; set; }
    [DataMember] public virtual ICollection<school> Nouns { get; set; }//school class in document class
    
    }


    • Marked as answer by Anne Jing Thursday, May 22, 2014 6:18 AM
    Friday, May 16, 2014 6:24 AM