你好,你能帮我吗?我有以下类别如何反序列化jsonconvert newtonsoft?
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; }
}
而且我需要反序列化下面的json。
{
"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"
]
}
即使改变的变量发生
不能反序列化JSON当前对象(例如{“名”:“值”})这个名字的错误保持 进式 “System.Collections中.Generic.List`1 [Foxconn.Portal.Model.HR.Training.EmpTraining]” 因为类型需要JSON阵列(例如[1,2,3]),以正确地反序列化 。
为了解决这个错误或者改变JSON到JSON阵列(例如 [1,2,3]),或改变它的反序列化类型,以便它是一个正常的.NET 类型(例如不是原始类型像整数,而不是类似数组或列表的集合类型 ),它们可以从JSON对象反序列化。 也可以将JsonObjectAttribute添加到该类型中,以强制它从一个JSON对象反序列化为 。
路径“EmployeesTrainings”,第1行,22位上
正在调用类反序列化代码是:
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>();
}
,我使用反序列化类是一个在下面。
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);
}
}
}
你的类和json之间没有相似之处。你还没有显示任何代码来映射这些。那么你的问题是什么? – Eser
错误信息的哪部分你不明白? – SLaks
你运行什么产生错误?你只显示类属性声明。 – romellem