且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何解决"Newtonsoft.Json.JsonSerializationException无法找到要用于类型的构造函数" Android错误?

更新时间:2023-01-17 23:21:29

背景:这是一个常见的问题,它源于UnityLinker的字节码剥离算法.发生的是,UnityLinker无法看到对类型构造函数的任何使用(因为Newtonsoft.Json仅通过反射来使用它,而编译器无法预见),因此将其删除.仅当使用IL2CPP脚本后端进行构建时,才会激活此字节码剥离,这就是为什么在PC上构建(或其他仅使用Mono的情况)构建时不会遇到任何问题的原因.

Background: This is a common problem that roots from the UnityLinker's bytecode stripping algorithms. What's happening is that the UnityLinker cannot see any use of your types constructor (as Newtonsoft.Json only uses it via reflection, which a compiler cannot foresee), so it removes it. This bytecode stripping is only activated when building with the IL2CPP scripting backend, which is why you didn't experience any problem when building on your PC (or any other solely using Mono for that matter).

修复程序::要解决此问题,您可以为该类型(甚至仅针对该构造函数)禁用字节码剥离.您可以使用link.xml文件执行此操作.示例:

The fix: To overcome this, you can disable bytecode stripping for that type (or even just for that constructor). You can do this using a link.xml file. Example:

<linker>
    <assembly fullname="MyAssembly">
        <type fullname="MyAssembly.MyCSharpClass">
            <!-- disables stripping just for the constructor -->
            <method signature="System.Void .ctor()"/>
        </type>

        <!-- disables stripping for the entire type -->
        <type fullname="MyAssembly.MyCSharpClass" preserve="all" />
    </assembly>
</linker>

我已经写了一些有用的页面,其中涉及使用link.xml以及其他工具来解决AOT问题,因为我发现Unity的文档缺乏而且分散: https://github.com/jilleJr /Newtonsoft.Json-for-Unity/wiki/Fix-AOT-using-link.xml

I've written some helpful pages on using link.xml among other tools to cope with AOT issues, as I find Unity's documentation to be lacking and scattered: https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/Fix-AOT-using-link.xml

要详细了解原因,请参阅我的说明页: https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/What-even-is-AOT

To read more about why this is, please refer to my explanation page: https://github.com/jilleJr/Newtonsoft.Json-for-Unity/wiki/What-even-is-AOT