How this repo makes Newtonsoft works on AOT? #147
-
If I try to use normal Newtonsoft on Unity + AOT Scripting Backend, its not secret, I'll get that exception: So how this repo handles this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Excellent question! On a higher level, I've filtered out the code that uses System.Reflection.Emit and other JIT-based code via a new build target. One key example of where this filtering is applied is at: And: The The official Newtonsoft.Json barely emits any IL explicitly, but instead uses some other constructs where you can convert syntax trees (AST) into IL quite easily, so it can on-the-fly generate functions that reads/writes to an object's fields which is increadibly faster than reading/writing via reflection. This means that the AOT build I've set up for Unity will never be as fast as Newtonsoft.Json running bare metal on a real CLR, but it's still increadibly fast. It only performs reflection to find the fields and properties once per type and caches the field's pointers in contracts. Originally the changes were quite minimal and were based on a comment by @dngulin (JamesNK#1440 (comment)), and can be found here: https://github.com/JamesNK/Newtonsoft.Json/pull/2044/files However as time went on, I found some more issues with IL2CPP and fixed them outside of that PR, as well as added other features such as:
A full list of all changes can be found here: JamesNK/Newtonsoft.Json@JamesNK:13.0.1...jilleJr:2a26db6 |
Beta Was this translation helpful? Give feedback.
Excellent question!
On a higher level, I've filtered out the code that uses System.Reflection.Emit and other JIT-based code via a new build target. One key example of where this filtering is applied is at:
https://github.com/jilleJr/Newtonsoft.Json-for-Unity/blob/2a26db68c98003f28749203378a3863afa5e6885/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs#L1405-L1426
And:
https://github.com/jilleJr/Newtonsoft.Json-for-Unity/blob/2a26db68c98003f28749203378a3863afa5e6885/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs#L514-L531
The
UNITY_LTS
pragma flag has been sprinkled across the repo to filter out some features. Newtonsoft.Json is built in such a way that it supports a lo…