JSON.NET Error Self referencing loop detected for type

后端 未结 25 3243
我在风中等你
我在风中等你 2020-11-22 02:16

I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used

JsonConvert.SerializeObject 

25条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 02:44

    Use JsonSerializerSettings

    • ReferenceLoopHandling.Error (default) will error if a reference loop is encountered. This is why you get an exception.
    • ReferenceLoopHandling.Serialize is useful if objects are nested but not indefinitely.
    • ReferenceLoopHandling.Ignore will not serialize an object if it is a child object of itself.

    Example:

    JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
    new JsonSerializerSettings 
    { 
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize
    });
    

    Should you have to serialize an object that is nested indefinitely you can use PreserveObjectReferences to avoid a StackOverflowException.

    Example:

    JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
    new JsonSerializerSettings 
    { 
            PreserveReferencesHandling = PreserveReferencesHandling.Objects
    });
    

    Pick what makes sense for the object you are serializing.

    Reference http://james.newtonking.com/json/help/

提交回复
热议问题