user9995363
user9995363

Reputation:

RestSharp Gets REST Data But Won't Deserialize

I'm trying to use RestSharp to get data from a REST web service. The service is returning data and I can see the JSON in the content string of the RestResponse object but no matter how many rows I insert into the database, the Data array of the RestResponse object only contains one entry and all of the fields are null.

Here is the Notification object

public class Notification
{
    [JsonProperty("message")]
    public string MessageText { get; set; }
    [JsonProperty("received")]
    public string NotificationDateTime { get; set; }
    [JsonProperty("effective")]
    public string EffectiveDateTime { get; set; }
    [JsonProperty("expiration")]
    public string ExpirationDateTime { get; set; }
    [JsonProperty("displayIsp")]
    public string DisplayAtIsp { get; set; }
    [JsonProperty("displayPos")]
    public string DisplayAtPos { get; set; }
    [JsonProperty("displayBow")]
    public string DisplayAtBow { get; set; }
    [JsonProperty("displayHandheld")]
    public string DisplayAtMobile { get; set; }
}

The web service call

        try
        {
            var restClient = new RestClient(new Uri(serviceUrl)) {ThrowOnAnyError = true};
            var restRequest = new RestRequest($"/{_companyCode}/{_storeNumber}/", Method.GET);
            var notifications = restClient.Execute<List<Notification>>(restRequest);

            Console.WriteLine();

        }
        catch (Exception exception)
        {
            Console.WriteLine( exception.Message );
        }

JSON data

{
    "notifications": [
        {
            "message": "test notification 09/29 17:39:49",
            "received": "09-29-2020 17:39:49",
            "effective": null,
            "expiration": null,
            "displayIsp": null,
            "displayPos": null,
            "displayBow": null,
            "displayHandheld": null
        },
        {
            "message": "test notification 09/29 17:39:49",
            "received": "09-29-2020 17:39:49",
            "effective": null,
            "expiration": null,
            "displayIsp": null,
            "displayPos": null,
            "displayBow": null,
            "displayHandheld": null
        }
    ],
    "companyNbr": 2,
    "storeNbr": 988
}

Upvotes: 0

Views: 253

Answers (1)

quaabaam
quaabaam

Reputation: 1972

Create a Notifications Root object that contains a list of your Notifications, and deserialize from the root.

public class NotificationsRoot
{
    [JsonProperty("notifications")]
    public List<Notification> Notifications { get; set; } 
    public int companyNbr { get; set; } 
    public int storeNbr { get; set; } 
}

And deserialize like so...

var notifications = restClient.Execute<NotificationsRoot>(restRequest);

Upvotes: 0

Related Questions