{"id":634,"date":"2023-09-21T11:54:01","date_gmt":"2023-09-21T17:54:01","guid":{"rendered":"https:\/\/kop.lat\/blog\/?p=634"},"modified":"2023-09-21T11:59:41","modified_gmt":"2023-09-21T17:59:41","slug":"how-to-resolve-the-system-text-json-jsonexception-error-maximum-allowed-depth-of-32","status":"publish","type":"post","link":"https:\/\/kop.lat\/blog\/how-to-resolve-the-system-text-json-jsonexception-error-maximum-allowed-depth-of-32\/","title":{"rendered":"How to resolve the &#8220;System.Text.Json.JsonException&#8221; error maximum allowed depth of 32."},"content":{"rendered":"\n<p><strong>Error<\/strong>:<br><strong><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. <\/mark><\/strong><\/p>\n\n\n\n<p>The error suggests that there is a cyclic reference within your <code>Comment<\/code> entities and their related <code>Commenter<\/code> entities, creating an infinite loop when serializing to JSON. <\/p>\n\n\n\n<p>This can happen when having bidirectional navigation properties between entities and trying to serialize them using the default JSON serialization settings, triggers an error (specifically an infinite loop).<\/p>\n\n\n\n<p>To fix this issue, can use the <code>ReferenceHandler.Preserve<\/code> option in the <code>JsonSerializerOptions<\/code> to handle cyclic references during JSON serialization.<\/p>\n\n\n\n<p>The code can be modified like this: <\/p>\n\n\n\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#5E69FF\"><div class=\"control-language\"><div class=\"dm-buttons\"><div class=\"dm-buttons-left\"><div class=\"dm-button-snippet red-button\"><\/div><div class=\"dm-button-snippet orange-button\"><\/div><div class=\"dm-button-snippet green-button\"><\/div><\/div><div class=\"dm-buttons-right\"><a id=\"dm-copy-raw-code\"><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\" style=\"display:none\">Copied<\/span><span class=\"dm-error-message\" style=\"display:none\">Use a different Browser<\/span><\/a><\/div><\/div><pre class=\" line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-clike\">using System.Text.Json;\nusing Microsoft.EntityFrameworkCore;\n\npublic ICollection&lt;Comment> GetCommentsByCommentAuthor(int commentAuthorId)\n{\n    var options = new JsonSerializerOptions\n    {\n        ReferenceHandler = ReferenceHandler.Preserve, \/\/ Add this line to handle cyclic references\n        \/\/ Other serialization options as needed\n    };\n\n    var comments = _context.Comments_dbs\n        .Where(p => p.Commenter.Id == commentAuthorId)\n        .ToList();\n\n    \/\/ Serialize the comments with the specified options\n    var serializedComments = JsonSerializer.Serialize(comments, options);\n\n    \/\/ Return the serialized comments as a JSON string\n    return serializedComments;\n}<\/code><\/pre><\/div><\/div>\n\n\n\n<p>In the code above:<\/p>\n\n\n\n<ol>\n<li>Created a <code>JsonSerializerOptions<\/code> instance and set the <code>ReferenceHandler<\/code> property to <code>ReferenceHandler.Preserve<\/code>. This option allows the JSON serializer to handle cyclic references by preserving references rather than following them endlessly.<\/li>\n\n\n\n<li>After retrieving the comments from the database, we used <code>JsonSerializer.Serialize<\/code> to serialize the comments to a JSON string using the specified options.<\/li>\n\n\n\n<li>Finally, returned the serialized comments as a JSON string. (this part of the code can be modified to return the JSON string or the deserialized objects, depending on requirements)<\/li>\n<\/ol>\n\n\n\n<p>This should help to avoid the cyclic reference issue and serialize <code>Comment<\/code> entities to JSON in a successull way.<\/p>\n\n\n\n<p>Addittionally, the property that is causing the infitinte look, can be converted into virtual, like this:<\/p>\n\n\n\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#7FC8A9\"><div class=\"control-language\"><div class=\"dm-buttons\"><div class=\"dm-buttons-left\"><div class=\"dm-button-snippet red-button\"><\/div><div class=\"dm-button-snippet orange-button\"><\/div><div class=\"dm-button-snippet green-button\"><\/div><\/div><div class=\"dm-buttons-right\"><a id=\"dm-copy-raw-code\"><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\" style=\"display:none\">Copied<\/span><span class=\"dm-error-message\" style=\"display:none\">Use a different Browser<\/span><\/a><\/div><\/div><pre class=\" line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-clike\">namespace blogpost.Models\n{\n    public class CommentAuthor\n    {\n        public int Id { get; set; }\n        public string Username { get; set; }\n        public virtual ICollection&lt;Comment> Comments { get; set;}\n    }\n}<\/code><\/pre><\/div><\/div>\n\n\n\n<p>It is also possible to completely ignore the infinite looping by adding an ignore option in Program.cs, like this:<\/p>\n\n\n\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#abb8c3\"><div class=\"control-language\"><div class=\"dm-buttons\"><div class=\"dm-buttons-left\"><div class=\"dm-button-snippet red-button\"><\/div><div class=\"dm-button-snippet orange-button\"><\/div><div class=\"dm-button-snippet green-button\"><\/div><\/div><div class=\"dm-buttons-right\"><a id=\"dm-copy-raw-code\"><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\" style=\"display:none\">Copied<\/span><span class=\"dm-error-message\" style=\"display:none\">Use a different Browser<\/span><\/a><\/div><\/div><pre class=\" no-line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-php\">builder.Services.AddControllers().AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);<\/code><\/pre><\/div><\/div>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Error:System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. The error suggests that there is a cyclic reference within your Comment entities and their related Commenter entities, creating an infinite loop when serializing to JSON. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":477,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[36,41,51,32,52,7],"tags":[42,53,54,124,123,122,125],"_links":{"self":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/634"}],"collection":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/comments?post=634"}],"version-history":[{"count":2,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/634\/revisions"}],"predecessor-version":[{"id":637,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/634\/revisions\/637"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/media\/477"}],"wp:attachment":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/media?parent=634"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/categories?post=634"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/tags?post=634"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}