Xamarin.Android 上的 JsonSerializationException 'Unable to find a constructor'

JsonSerializationException 'Unable to find a constructor' on Xamarin.Android

我的代码有这个非常奇怪的问题,这是一个相当新的问题,考虑到半年前我还没有遇到过。长话短说,我在 Xamarin 中制作了一个应用程序,并于大约半年前在所有 3 家商店(App Store、Google Play 和 Microsoft Store)上发布了它。

昨天一位用户报告了 Android 应用程序的问题,在我修复并重新编译之后,我现在遇到 Json.NET

的新错误

例外是

Newtonsoft.Json.JsonSerializationException: Unable to find a constructor to use for type Rowlog.Common.Dtos.CompressedTripData. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'tripCoordinates', line 1, position 19.

在你问之前,是的 Rowlog.Common.Dtos.CompressedTripData 确实有一个无参数的构造函数(好吧,它根本没有,我们都知道这是一回事)。

就像我说的,这是我从 Android 设备上的服务器加载 CompressedTripData 对象的时候。在 iOS 和 Windows Phone 上加载完全相同的对象可以顺利进行。 我猜这一定是 Json.NET 或 Xamarin.Android 最近发生的变化导致的(其他应用程序仍在使用大约半年前的 Json.NET 库。不是确定自那以后是否有任何更新)

有没有其他人遇到过类似的问题,如果有,你是如何解决的?

在项目属性的 'Android options' 选项卡中,有一个 'linker' 选项卡。 在 'Linking' 下拉列表中选择的选项是 "Sdk Assemblies only" 还是 "Sdk and user assemblies"?

如果是后者,链接时会跳过无参构造函数,因为没有检测到使用。所以将其更改为 "Sdk Assemblies only".

Preserve 属性是一种更有针对性的方法,可以确保链接器不会删除成员(如果您仍然希望它通常对您的代码执行此操作)。

示例:

[Preserve]
[JsonConstructor]
private AlertRequest(bool fake_arg)
{
    // fake_arg is to have a unique ctor that we exclusively
    // use in JSON de-serialization via JsonConstructor attribute.
    // Preserve attribute ensures Xamarin linker does not remove,
    // as there are no direct uses of this ctor in the code base
}