Manish Sharma
Manish Sharma

Reputation: 2426

JsonSerializationException 'Unable to find a constructor' on Xamarin.Android with .NET Standard Library

I have used Xamarin Native UI for Android application and Created different class library for API call and data Deserialize api data using Newtonsoft.Json.

That class library Target Framework is .NET Standar 2.0.

As I have added that reference to the console application so its working fine but same reference i have add in Android project its throw error.

**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.

As per error message i have used attribute JsonConstructor for default constructor of class.

Example:

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

    }
}

Upvotes: 2

Views: 1943

Answers (2)

SushiHangover
SushiHangover

Reputation: 74134

As PreserveAttribute required Mono.Android.dll Or 'Xamarin.iOS.dll' reference in that but my class library is Common for both thats why it is not possible

Add a PreserveAttribute class to your class library and use that attribute as the Mono Linker only uses the "name" of the attribute and not the namespace/classname...

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

And then use that attribute on your JSON model/class:

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

Upvotes: 3

Arvind Chourasiya
Arvind Chourasiya

Reputation: 17422

Try using PreserveAttribute at the top of your class

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

}

add one more class PreserveAttribute in class library

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

Edit Linking- Sdk & user assemblies

Skip linking assemblies- Newtonsoft.Json;

add Newtonsoft.Json in your Skip linking assemblies option

Upvotes: 1

Related Questions