【问题标题】:JsonSerializationException 'Unable to find a constructor' on Xamarin.Android with .NET Standard Library带有 .NET 标准库的 Xamarin.Android 上的 JsonSerializationException“找不到构造函数”
【发布时间】:2018-10-04 05:45:19
【问题描述】:

我已经为 Android 应用程序使用了 Xamarin Native UI,并为 API 调用和数据创建了不同的类库使用 Newtonsoft.Json 反序列化 api 数据。

那个类库目标框架是.NET Standar 2.0

由于我添加了对控制台应用程序的引用,因此它工作正常,但我在 Android 项目中添加了相同的引用,它的抛出错误。

**Error Details** Newtonsoft.Json.JsonSerializationException: Unable to find a constructor to use for type. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.

根据错误消息,我已将属性 JsonConstructor 用于类的默认构造函数。

例子:

public class TestClass
{
    [JsonConstructor]
    public TestClass()
    {

    }
}

【问题讨论】:

  • 您遇到错误的构建配置的 Mono Linker 设置是什么。
  • @SushiHangover Sdk 和用户程序集。
  • 在 Arvinfraja 的回答中使用 PreserveAttribute

标签: c# xamarin xamarin.forms xamarin.android json.net


【解决方案1】:

由于 PreserveAttribute 需要 Mono.Android.dll 或 'Xamarin.iOS.dll' 引用,但我的类库对于两者都是通用的,这就是为什么它不可能

PreserveAttribute 类添加到您的类库并使用该属性,因为 Mono 链接器仅使用属性的“名称”而不使用命名空间/类名...

public sealed class PreserveAttribute : Attribute
{
    public bool AllMembers;
    public bool Conditional;
    public PreserveAttribute (bool allMembers, bool conditional)
    {
        AllMembers = allMembers;
        Conditional = conditional;
    }
    public PreserveAttribute ()
    {
    }
}

然后在您的 JSON 模型/类上使用该属性:

[Preserve(AllMembers = true)]
public class TestClass
{
  ~~~

【讨论】:

    【解决方案2】:

    尝试在班级顶部使用PreserveAttribute

    [PreserveAttribute(AllMembers = true)]
    public class TestClass
    {   
        public TestClass() {}
    
    }
    

    在类库中再添加一个类PreserveAttribute

    public sealed class PreserveAttribute : System.Attribute
    {
        public bool AllMembers;
        public bool Conditional;
    }
    

    编辑 链接 - SDK 和用户程序集

    跳过链接程序集 - Newtonsoft.Json;

    在您的跳过链接程序集选项中添加Newtonsoft.Json

    【讨论】:

    • 这适用于 Xamarin 表单,但不适用于 Native ui,我为 Api 调用和业务逻辑采用了适用于 Android 和 iOS 的单独类库。
    • 即使我将 PCL 与 xamarin.android 一起使用,同样的属性也适用于我。几天前我收到了这个错误,
    • 在同一个 android 项目中你可以这样做,但如果我有不同的类库用于公共逻辑,而在那个公共库中我不能这样做。
    • @ManishSharma - 在您的类库中添加一个名为 PreserveAttribute 的密封类。我之前忘了提。如果仍然无法正常工作,请尝试关注我的编辑部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    相关资源
    最近更新 更多