"Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class

25,095

Solution 1

You need to have an empty constructor in Currency class in order to deserialize it.

Solution 2

One other thing might cause this issue is if you have a full linking enabled in your android project. you need to preserve class and members using

[Runtime.Preserve(AllMembers = true)]
public class Currency
{}
Share:
25,095
Nika Kurdadze
Author by

Nika Kurdadze

Java/Kotlin & Android Developer. Software design enthusiast.

Updated on July 09, 2022

Comments

  • Nika Kurdadze
    Nika Kurdadze almost 2 years

    I am developing an app in Xamarin Android. I have a splash screen where I serialize a class and pass it to MainActivity using Intent. When I try to deserialize it in MainActivity I get an error message :

    "SerializationException unable to find constructor to use for types" 
    

    Serialization :

    void LoadData() {
        Currency currency = new Currency(this);
        intent = new Intent(this, typeof(MainActivity));
        intent.PutExtra("currency", Newtonsoft.Json.JsonConvert.SerializeObject(currency));
        StartActivity(intent);
    }
    

    Deserialization :

    cur = Newtonsoft.Json.JsonConvert.DeserializeObject<Currency> (Intent.GetStringExtra("currency")); // I get the error here
    

    Class constructor :

    public Currency(Context context) {
        thiscontext = context;
    }
    

    I began experiencing this problem after I added the parameter Context context to the constructor. What has caused this? How can I solve it? Is it possible to serialize/deserialize class which has parameters?

  • dampee
    dampee over 7 years
    Not really, you could have solutions like this: stackoverflow.com/a/28155770/97615
  • Daniel
    Daniel about 4 years
    you almost got it correct here... it was the linking type on the option => build iOS
  • Emil
    Emil about 4 years
    @Daniel yes Ios has similar behavior. I wrote Android because question was for android. it can be applied for Ios as well
  • Luke Alderton
    Luke Alderton about 4 years
    You're right, this issue seems to also be caused by the most recent Xamarin guidance to enable full linking to get around Xamarin.Forms using a deprecated API in the iOS app.