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

时间:2015-06-26 09:45:28

标签: c# android json xamarin deserialization

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?

2 个答案:

答案 0 :(得分:7)

您需要在Currency类中有一个空构造函数才能反序列化它。

答案 1 :(得分:3)

另一件事可能会导致此问题,如果您在Android项目中启用了完整链接。你需要使用

保留班级和成员
[Runtime.Preserve(AllMembers = true)]
public class Currency
{}