Mateusz Kilinski Mateusz Kilinski - 1 month ago 26
C# Question

C# Deserialize JSON to Object

I have a little problem with C# program. It is my first program in C# so please - be forgiving :)

I would like to deserialize my json file into object, but I don't know how my class should be built. Im using Newtonsoft JSON lib.

JSON file:


http://api.nbp.pl/api/exchangerates/tables/A/last/?format=json





Form1.cs:

private void button1_Click(object sender, EventArgs e)
{
CurrencyCodeValues k = new CurrencyCodeValues();
WebClient myWebClient = new WebClient();
dynamic result = myWebClient.DownloadString("http://api.nbp.pl/api/exchangerates/tables/A/last/?format=json");
IList<CurrencyCodeValues> m = JsonConvert.DeserializeObject<CurrencyCodeValues>(result);
}





Class1.cs:

class CurrencyCodeValues
{
public string table { get; set; }
public string no { get; set; }
public string effectiveDate { get; set; }
public List<rates_> rates { get; set; }

}

public class rates_
{
public string currency { get; set; }
public string code { get; set; }
public float mid { get; set; }
}





Error message:


Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WindowsFormsApplication4.CurrencyCodeValues' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.

Answer

As your error message suggest your class should look like this

public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public string table { get; set; }
    public string no { get; set; }
    public string effectiveDate { get; set; }
    public Rate[] rates { get; set; }
}

public class Rate
{
    public string currency { get; set; }
    public string code { get; set; }
    public float mid { get; set; }
}

and then deseralize it like

JsonConvert.DeserializeObject<Rootobject>(result);