I am trying to deserialize a JSON return from a RestSharp call to an API.
This is a C# console application. Here is my code so far:
using System;
using RestSharp;
using RestSharp.Authenticators;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RestSharp.Deserializers;
using System.Collections.Generic;
namespace TwilioTest
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("https://api.twilio.com/2010-04-01");
var request = new RestRequest("Accounts/{{Account Sid}}/Messages.json", Method.GET);
request.AddParameter("To", "{{phone number}}");
request.AddParameter("From", "{{phone number}}");
client.Authenticator = new HttpBasicAuthenticator("{{account sid}}", "{{auth token}}");
var response = client.Execute(request);
var jsonResponse = JsonConvert.DeserializeObject(response.Content);
Console.WriteLine(jsonResponse);
}
}
}
The response is a JSON-formatted list of messages, with keys including "to", "from", "body", and "status". Here's sort of what that looks like:
{
"to": "{{phone number}}",
"from": "{{phone number}}",
"body": "Sent from your Twilio trial account - Message 1!",
"status": "delivered"
},
{
"to": "{{phone number}}",
"from": "{{phone number}}",
"body": "Sent from your Twilio trial account - Message 2",
"status": "delivered"
},
I want to turn that into an array of Message objects, with a Message class that looks like this:
class Message
{
public string To { get; set; }
public string From { get; set; }
public string Body { get; set; }
public string Status { get; set; }
}
I've been looking around for how to turn JSON into objects and found this page: http://blog.atavisticsoftware.com/2014/02/using-restsharp-to-deserialize-json.html. The third example on the page is along the lines of what I want.
I made some changes to the program and now it looks like this:
class Program
{
static void Main(string[] args)
{
// same as above until this point
...
var response = client.Execute(request);
JsonDeserializer deserial = new JsonDeserializer();
var messageList = deserial.Deserialize<List<Message>>(response);
foreach (Message element in messageList)
{
Console.WriteLine("To: {0}", element.To);
Console.WriteLine("From: {0}", element.From);
Console.WriteLine("Body: {0}", element.Body);
}
Console.ReadLine();
}
}
However, messageList is empty when I run the program. What am I missing to turn the JSON response into a list of objects? The RestSharp Documentation makes it look fairly straightforward.