如何反序列化jsonconvert newtonsoft?

时间:2016-04-19 20:31:42

标签: c# json json-deserialization

大家好,你能帮助我吗?我有以下课程

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对象(例如{“name”:“value”})   进入类型   'System.Collections.Generic.List`1 [Foxconn.Portal.Model.HR.Training.EmpTraining]'   因为该类型需要一个JSON数组(例如[1,2,3])来反序列化   正确。

     

要修复此错误,请将JSON更改为JSON数组(例如   [1,2,3])或更改反序列化类型,使其成为正常的.NET   type(例如,不是像整数这样的基本类型,不是集合类型   像数组或List一样,可以从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);
                }
            }
        }

2 个答案:

答案 0 :(得分:1)

您好,您可能需要使用以下类才能将您的json数据转换为类对象

public class EmployeesTraining
{
    public int CODCOLIGADA { get; set; }
    public string CHAPA { get; set; }
    public string NOME { get; set; }
    public string CCUSTO { get; set; }
    public string Departamento { get; set; }
    public string CODPOSTO { get; set; }
    public string POSTO { get; set; }
    public string TREINAMENTO { get; set; }
    public string REALIZADO_EM { get; set; }
    public string VALIDADE { get; set; }
}

public class RootObject
{
    public List<EmployeesTraining> EmployeesTrainings { get; set; }
    public bool HasErrors { get; set; }
    public List<string> Errors { get; set; }
}

然后,您可以查看EmployeeTrainings列表以访问个人员工详细信息

使用以下链接将您的json数据转换为C#c​​lasses http://json2csharp.com/

答案 1 :(得分:1)

您可以使用attributes更改序列化字段的名称:

public class EmpTraining
{
    [JsonProperty('CODCOLIGADA')]
    public int CodColig { get; set; }
    [JsonProperty('CHAPA')] 
    public string EmpID { get; set; }
    [JsonProperty('NOME')]      
    public string Employee { get; set; }
    [JsonProperty('CCUSTO')]            
    public string CostCenter { get; set; }
    [Jsonproperty('Departamento')]
    public string Department { get; set; }
    [JsonProperty('CODPOSTO']
    public string WorkstationID { get; set; }
    [JsonProperty('POSTO')]
    public string Workstation { get; set; }
    [JsonProperty('TREINAMENTO')]
    public string Training { get; set; }    
    [JsonProperty('REALIZADO_EM')]  
    public string CreateDt { get; set; }
    [JsonProperty('VALIDADE')]  
    public string DueDt { get; set; }
}

但是 您提供的错误消息无法正确解释您的问题。它说:

  

无法将当前JSON对象(例如{“name”:“value”})反序列化为类型'System.Collections.Generic.List`1 [CoderwallDotNet.Api.Models.Account]'

因此似乎还有另一个问题,无法回答。请提供完整的代码示例,否则只是在猜测。