I am using System.Text.Json version 6.0 to deserialize a int array. Example:
var array = System.Text.Json.JsonSerializer.Deserialize<int[]>("[1, 2]");
If I try to run this on Android with IL2CPP compilation method it crashes with:
Error Unity ExecutionEngineException: Attempting to call method 'System.Text.Json.Serialization.Converters.ArrayConverter`2[[System.Int32[ ], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]::.ctor' for which no ahead of time (AOT) code was generated.
Yeah, stay away from System Text Json and also from the in-built JSON, unless it’s all you need.
Problems with Unity “tiny lite” built-in JSON:
In general I highly suggest staying away from Unity’s JSON “tiny lite” package. It’s really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes and ALL properties.
Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window → Package Manager).
While choosing a proper json library is vital, I don’t think switching to Json.NET would change anything. The issue here is that IL2CPP has never encountered your code calling the int array constructor so it was not included in the AOT compiled code. The library tries to create an instance of an int array, but the constructor is missing. It may be a different problem, but try adding this in your class:
protected int[] _dummy = new int[0];
This should cause the compiler to include the int array constructor. I’m sure there are other ways to tell the compiler to not strip certain classes / methods. AFAIK there’s an IL2CPP config.
Looks like you didn’t read the error message. The error isn’t “int array constructor” but the constructor of a generic type needed to perform type-specific serialization and deserialization.
If you upgrade to the latest 2021.3 editor version, you should have access to a setting in the build settings window that says “Faster (smaller) builds” for IL2CPP to generate versions of generic code that don’t require a specialized implementation per used type argument type.
Yes, you’re right I overlooked the generic part. I’ve also found that the latest Unity version had some fixes for generic type AOT compilation. Though if you can’t upgrade the Unity version, Just declaring an instance of the class should also fix the issue. Unfortunately the ArrayConverter class is an internal class, so we can’t create an instance of a certain concrete class manually. The issue was mentioned here on github where josh (from Unity) announced that since 2021.2 alpha they added generic support even for value types when compiling with IL2CPP.
Though there are other workaround like implementing your own conversion wrapper. It’s not that great but according to the conversation it seems that it worked.