How to deserialize jsonconvert newtonsoft?

丶灬走出姿态 提交于 2019-12-25 18:23:48

问题


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);
                }
            }
        }

回答1:


Hi you probably need to use the below class in order to convert your json data to class object

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; }
}

You could then look through EmployeeTrainings list for accesing individual employee details


use the below link to convert your json data to C# classes http://json2csharp.com/




回答2:


You can use attributes to change the name of the serialized fields:

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; }
}

But the error message you supplied does not explain your problem correctly. It says:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[CoderwallDotNet.Api.Models.Account]'

so there seems to be another problem around, which can not be answered. Please supply your full code example, otherwise were just guessing.



来源:https://stackoverflow.com/questions/36728863/how-to-deserialize-jsonconvert-newtonsoft

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!