Newtonsoft JSON code-stripping level must be "low" for WebGL

Pretty much what’s in the title.

We are using Unity 6 but haven’t tried this on earlier versions, so may apply to others.

We are developing a WebGL game for a customer. We are using Unity’s provided Newtonsoft JSON package because we send messages across our game server that required us to write a custom deserializer. This works fine in the editor, however when we build and test in-browser we get an error that it is unable to find the constructor for the deserializer class (which is public and marked System.Serializable).

We eventually figured out WebGL is happy if we set Optimization → Managed Stripping Level to “Low”. It had previously been set to high, but also didn’t work on medium.

Is there a way to configure Newtonsoft to work with higher code-stripping levels?

Thanks!

There has been a recent discussion, maybe the solution in there is all that’s needed.

There’s also the Preserve keyword and other config options. But you have to spend time to analyze what gets stripped that shouldn’t.

Hi!

Would it be possible for you to use JsonUtility instead? Unity - Scripting API: JsonUtility
Newtonsoft.Json will increase your build by quite a lot especially if you need to lower to Managed Stripping Level. This will increase load time of your build.
Is there something preventing you from using JsonUtility?

I also use Newtonsoft.Json though in 2022 LTS so far. I have Low Stripping too - the same issue with constructors otherwise…

While I do not remember exact reasons jsonUtility is not up to the task (is it focused on fields not properties if Unity serializer?) Newtonsoft is just a much more complete solution and easier to work with for say inheritance than System.Text.Json

FYI the build is bigger…, but load time is very fast

The Preserve keyword is what I needed. Thanks! I applied it to the constructor and other accessors for my data class that weren’t being directly used in the code.

Funny I knew about link.xml but I’d never looked at the docs closely enough to see that the preserve attribute was another way to go about it.

JsonUtility wasn’t able to deal with the List of interface objects I needed to process.

JsonUtility is able to serialize them granted they’re decorated with the [SerializeReference] attribute, and follows the other rules specified in the docs: Unity - Scripting API: SerializeReference