HeisenBerg HeisenBerg - 5 months ago 276
JSON Question

C# json.net: not able to deserialize

This is the example json from json.net website

public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}


usage:

string json = @"{
'Email': 'james@example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";

Account account = JsonConvert.DeserializeObject<Account>(json);

Console.WriteLine(account.Email);


But when I run it I'm getting error:


Unable to find a constructor to use for type Gogch.Account. A class
should either have a default constructor, one constructor with
arguments or a constructor marked with the JsonConstructor attribute.
Path 'Email', line 1, position 9.


I added an empty constructor as said in another topic, but I'm still getting the same error. Any help is appreciated.

Answer

As the error says. Your class needs to have a default constructor. A default constructor is one that doesn't have an parameters. Try adding an empty constructor to your class and see if that works:

public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreateDate { get; set; }
    public IList<string> Roles { get; set; }

    [JsonConstructor]
    public Account() { }
}

In the 'Android options' tab of the project properties, there is a 'linker' tab. Is the selected option in the 'Linking' dropdown "Sdk Assemblies only" or is it "Sdk and user assemblies"?

If it is the latter, the parameterless constructor is skipped when linking, because no use is detected. So change it to "Sdk Assemblies only". http://stackoverflow.com/a/27938638/3603938