JsonSerializationException'无法找到构造函数'在Xamarin.Android上

时间:2015-01-14 08:23:56

标签: c# android xamarin json.net 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库。不确定是否有过自那以后的任何更新

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

2 个答案:

答案 0 :(得分:20)

在项目属性的“Android选项”选项卡中,有一个“链接器”选项卡。 “链接”下拉列表中的选定选项是“仅限Sdk程序集”还是“Sdk和用户程序集”?

如果是后者,则链接时会跳过无参数构造函数,因为未检测到任何用途。因此,将其更改为“仅限Sdk Assemblies”。

答案 1 :(得分:1)

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
}
相关问题