I'm using newtonsoft json to deserialize a json string and write the contents into a datatable, run into errors. I'm able to get this working with JavaScriptSerializer class but not with newtonsoft json. Please point me where I am doing it wrong.
Please find json sample below.
JSON:
[{
"Id": 1,
"FirstName": "Jason1",
"LastName": "Test1",
"Email": "123@automail.com",
"Eligible": true,
"InsertLogtime": "2022-02-21T00:51:59.917",
"Comment": null
},
{
"Id": 2,
"FirstName": "Jason2",
"LastName": "Test2",
"Email": "234@automail.com",
"Eligible": true,
"InsertLogtime": "2022-02-21T00:51:59.917",
"Comment": null
}
]
C#:
public class Profile
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public bool Eligible { get; set; }
public DateTime InsertLogtime { get; set; }
public object Comment { get; set; }
}
public class Root
{
public List<Profile> profile { get; set; }
}
var jstring = JsonConvert.DeserializeObject<Root>(profile);
//string profile has data in the sample specified
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(int)));
dt.Columns.Add(new DataColumn("FirstName", typeof(string)));
dt.Columns.Add(new DataColumn("LastName", typeof(string)));
DataRow dr = dt.NewRow();
for (int i = 0; i < jstring.profile.Count; i++)
{
try
{
dr = dt.NewRow();
dr["Id"] = jstring.profile[i].Id;
dr["FirstName"] = jstring.profile[i].FirstName;
dr["LastName"] = jstring.profile[i].LastName;
dt.Rows.Add(dr);
}
}
Error:
Cannot deserialize the current JSON array because the type requires a JSON object to deserialize correctly. To fix this error either change the JSON to a JSON object or change the deserialized type to an array or a type that implements a collection interface 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.
This
[{
"Id": 1,
"FirstName": "Jason1",
"LastName": "Test1",
"Email": "123@automail.com",
"Eligible": true,
"InsertLogtime": "2022-02-21T00:51:59.917",
"Comment": null
},
{
"Id": 2,
"FirstName": "Jason2",
"LastName": "Test2",
"Email": "234@automail.com",
"Eligible": true,
"InsertLogtime": "2022-02-21T00:51:59.917",
"Comment": null
}
]
Is an array ([......]). So as the error says you must deserialze into an array
Like this
JsonConvert.DeserializeObject<Profile[]>(profile);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.