Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

How do serialization libraries, like Newtonsoft JSON.net, work on platforms like iOS/Blazor/Unity that use AOT? Doesn’t seem like anything special has to be done other than reference the Nuget package and it’s just working?


There has been a push for using Source Generators to move stuff that relies on reflection to compile time code generation. JSON serialization is (mostly) supported in this mode with perf advantages as well.

This does not address pre-existing packages obviously. To make them work with AOT you might need to include an XML file (rd.xml) that indicates all the types that could be dynamically generated in your code. It is quite brittle and AFAIK everything might work until you get a runtime failure if something you did not include ends up being constructed.


And when stuff does inevitably break once deployed to production, it can be really difficult to pinpoint the reason why.

I've stopped using AOT, as IMO it's not (currently) suitable for complex, real-world apps - unless you are prepared for a lot of testing and pain.


With Unity/IL2CPP stuff: For general-purpose serialization libraries like JSON, you sometimes need to provide hints to make sure types are included: https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/Fi...

For schema serialization on known types, there are codegen tools (i.e. moc for MessagePack): https://github.com/neuecc/MessagePack-CSharp

MessagePack is migrating to Rosalyn code generators, so basically invisible codegen. Cysharp's newer serialization library, MessagePack, already uses this: https://github.com/Cysharp/MemoryPack


memorypack looks interesting but the page omits a payload size comparison so who knows how good it really is


I was able to use aot and System.Text.Json in a test app. You only need to put an attribute on a class to specifying the type info, and then pass a type enum when you serialize/deserialize. I was surprised how easy it was because I had been really concerned about reflection based stuff like json.


As I understand it, Mono supports reflection when compiling AOT, so serializing using reflection would work.

With a newish .NET they don't need reflection for AOT code, as JSON libraries can use source generators instead.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: