vpenades / SharpGLTF

glTF reader and writer for .NET Standard
MIT License
457 stars 72 forks source link

`JsonContent.Serialize()` throw `System.NullReferenceException` when some collection count = 0 #105

Closed LovingEvil closed 3 years ago

LovingEvil commented 3 years ago

sharpgltf.core.1.0.0-alpha0023 JsonContent.Serialize(object) object with empty collection - throw System.NullReferenceException. object with collection = null - no Exception.

Approximate object structure:

Serialization is executed without options.

StackTrace: at SharpGLTF.IO._JsonArray.TryClone(IEnumerable collection)

Is this intended behavior or is there something wrong?

vpenades commented 3 years ago

Yes, the glTF schema forbids empty collections as they're considered a waste of resources. Empty arrays should be replaced by nulls.

LovingEvil commented 3 years ago

Ok. I have to keep track of this in my code? ShaprGLTF doesn't have collection preprocessing tools? Some best practices in this case... 🙄

vpenades commented 3 years ago

Internally, the library does handle these cases for the main schema but I am guessing your having these issues with the Extras property?

LovingEvil commented 3 years ago

Yes, and I did not immediately understand what the problem was. The sources for collecting data for writing to extras are different, empty collections have not been encountered before, and everything worked. Now I am checking all collections from the object before JsonContent.Serialize(object).

Like this:

foreach (item in object)
{
  if (item.Collection.Count == 0)
  {
      item.Collection = null;
  }

  // other collections checks (with subCollections)
}
vpenades commented 3 years ago

The problem with json serialization is that the whole architecture is designed to expect a schema; everything in glTF works with a schema, except for the extras field. So all the provisions I made for the main schema do not apply for extras.

So for now you should check for empty collections in the extras field. I'll try to find a better solution for the next version

LovingEvil commented 3 years ago

Thanks for the explanation and your work on sharpGLTF!

vpenades commented 2 years ago

fixed in this commit