I am new to json and am trying to write code to import a file which looks like the following:
<pre lang="xml">
{
"name": "John",
"joined": "2010/5/4 21:57:34",
"title": "Area Manager",
"languages": [{"id":1,"name":"C#"},{"id":2,"name":"VB.NET"}],
"speaks":
[
{"id":5,"language":"English"},
{"id":6,"language":"French"}
],
"products":
[
{"product_id":"36847f8001cd1","name":"Bolt Free"},
{"product_id":"36847f8001cd7","name":"Oil4All"}
],
"areas":
{"countries":
[
{"iso_3166_1":"US", "release_date":"1997-02-13"},
{"iso_3166_1":"DE", "release_date":"1997-05-21"},
]
}
}
Using NuGet I have installed the Newton.Json package. The code to read the file looks like this:
using (System.IO.StreamReader r = new System.IO.StreamReader(src))
{
string json = r.ReadToEnd();
EmployeeInfo item = Newtonsoft.Json.JsonConvert.DeserializeObject<EmployeeInfo>(json);
}
The Item class is defined as follows:
public class EmployeeInfo
{
public string name;
public DateTime joined;
public String title;
public List<Languages> languages;
public List<Speaks> speaks;
public List<Products> products;
public List<Areas> areas;
public class Languages
{
public int id;
public String name;
}
public class Speaks
{
public int id;
public String language;
}
public class Products
{
public String product_id;
public String name;
}
public class Areas
{
public String iso_3166_1;
public DateTime release_date;
}
}
When I run the code I get an unhandled exception which says:
“Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WindowsFormApp.EmployeeInfo+Areas]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.”
Can anyone tell me what I am doing wrong and how to get the last item deserialized correctly?
Thanks in advance.