Search code examples
c#restsharpjson-deserialization

Restsharp Issues Deserialising


I'm trying to deserialise a JSON which conatains a series of "Clients" in succession from an API Call:

{"resource":[{"ClientID":1,"ClientName":"Name 1","ClientIntID":"TEST001","ClientCreatedDate":"2018-05-10 00:00:00"},{"ClientID":2,"ClientName":"Name 2","ClientIntID":"TEST002","ClientCreatedDate":"2018-05-10 03:10:47"},{"ClientID":3,"ClientName":"TestAPI","ClientIntID":"API001","ClientCreatedDate":"2018-05-10 03:30:14"},{"ClientID":4,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:03:40"},{"ClientID":5,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:04:28"},{"ClientID":6,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:04:31"},{"ClientID":7,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:10:32"},{"ClientID":8,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:10:35"}]}

into a List of Clients.

This is my code to deserialise:

        IRestResponse<List<Client>> response = restClient.Execute<List<Client>>(request);
        var content = response.Content;
        var data = response.Data;

        //Trying to check output of each Client in List:
        foreach(Client c in data)
            {
                Console.WriteLine(c.ClientName);
            }

This is my Client Class:

    public class Client
{
    public int ClientID { get; set; }
    public string ClientName { get; set; }
    public string ClientIntID { get; set; }
    public string ClientCreatedDate { get; set; }

}

I'm getting a list that is null, however when I change the code to simply cast into one Client only, it correctly stores the first client in the JSON response.

Any tips?


Solution

  • Your answer is in the form of the following format, so you have to deserialize into RootObject

    public class Resource {
        public int ClientID { get; set; }
        public string ClientName { get; set; }
        public string ClientIntID { get; set; }
        public string ClientCreatedDate { get; set; }
    }
    
    public class RootObject{
        public List<Resource> resource { get; set; }
    }