Hello guys Could you help me? I have the class below
public class EmpTraining
{
public int CodColig { get; set; }
public string EmpID { get; set; }
public string Employee { get; set; }
public string CostCenter { get; set; }
public string Department { get; set; }
public string WorkstationID { get; set; }
public string Workstation { get; set; }
public string Training { get; set; }
public string CreateDt { get; set; }
public string DueDt { get; set; }
}
And I need to deserialize the json below.
{
"EmployeesTrainings": [
{
"CODCOLIGADA": 1,
"CHAPA": "sample string 2",
"NOME": "sample string 3",
"CCUSTO": "sample string 4",
"Departamento": "sample string 5",
"CODPOSTO": "sample string 6",
"POSTO": "sample string 7",
"TREINAMENTO": "sample string 8",
"REALIZADO_EM": "2016-04-19T14:17:19.7291778-03:00",
"VALIDADE": "2016-04-19T14:17:19.7291778-03:00"
},
{
"CODCOLIGADA": 1,
"CHAPA": "sample string 2",
"NOME": "sample string 3",
"CCUSTO": "sample string 4",
"Departamento": "sample string 5",
"CODPOSTO": "sample string 6",
"POSTO": "sample string 7",
"TREINAMENTO": "sample string 8",
"REALIZADO_EM": "2016-04-19T14:17:19.7291778-03:00",
"VALIDADE": "2016-04-19T14:17:19.7291778-03:00"
}
],
"HasErrors": true,
"Errors": [
"sample string 1",
"sample string 2"
]
}
Even changing the name of the variables the error keep happening
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type
'System.Collections.Generic.List`1[Foxconn.Portal.Model.HR.Training.EmpTraining]'
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) 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.
Path 'EmployeesTrainings', line 1, position 22.
The code that is calling the class to deserialize is:
public static List<EmpTraining> List(int codColig, string empID, string trainingID, string workstationID, string status, int? days)
{
List<EmpTraining> empList = Api.PostWebApiStr<List<EmpTraining>>(JSON, webApi, Token, timeOut);
if (empList.Count > 0)
return empList;
return new List<EmpTraining>();
}
the class that I'm using to deserialize is that one below.
public static T PostWebApiStr<T>(string data, Uri webApiUrl, Token token, int timeout)
{
using (var client = new ExtendedWebClient(webApiUrl, timeout))
{
try
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
if (token != null)
{
client.Headers[HttpRequestHeader.Authorization] = string.Format("{0} {1}", token.TokenType, token.AccessToken);
}
var response = client.UploadString(webApiUrl, data);
return JsonConvert.DeserializeObject<T>(response);
}
catch (WebException ex)
{
throw new Exception(ex.Message);
}
}
}
See Question&Answers more detail:
os