Correctly resolve "Serialization depth limit 10 exceeded"

I have a json object that I am requesting from server structured like so …

{
   "objects":[
      {
         "nestedObjects":[
            {
               "nestedObjects":[
                 
               ]
            }
         ]
      }
   ]
}

I want to parse this into a structure like so …

// main object
[System.Serializable]
public sealed class SData
{
  [SerializeField] private List<SObject> objects = new List<SObject>();
  public List<SObject> Objects { get => objects; }
}

//object
[System.Serializable]
public sealed class SObject
{
  [SerializeField] private List<SObject> nestedObjects = new List<SObject>();
  public List<SObject> nestedObjects { get => nestedObjects; }
}

As you can see in the json each object contains an array of objects which contains an array of objects …
The csharp object contains a list of objects of the same type …

Basic tree structure.

I don’t know how deep the nesting may go, at times it may go beyond Unity’s limit of 10 (to avoid infinite).

What is the proper method to resolve this issue?

One way might be to parse the JSON yourself, one token at a time, and stand up the data structure you want.

I would recommend using the Newtonsoft JSON .NET to parse it… you will write code that will call things like “get next token” and “get next object” and stuff like that, and the shape of your code will need to have concordance with your data structure.

I would be more specific but it has been years since I manually parsed JSON this way, so definitely check the docs and see what tutorials you can find about manual parsing.

1 Like

More often than not, such deep nesting indicates a flawed design.

Recently there was some other thread where the hierarchy was books-chapters-sections-articles-bla-bla-and-so-forth-subsections-comments. Something like that could as well be a flat list, like in a database, where each of the lowest-level item contains all the information, for instance every comment could have an article, section, chapter and book identifier. This trades some memory for faster traversal and easier storage.

Alternatively, you’d only have a single list of comments and each comment has the ID of the subsection it is in. Then you have a list of subsections, each of which has an ID of “and-so-forth”. Until you arrive at the list of chapters, each of which has the ID of the book it is in.

In database speak this is called “normalization”: Database normalization - Wikipedia

1 Like