5

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.

1 Answer 1

3

I don't know much about RestSharp, but you can get the response content string like that :

var responseContent = client.Execute(request).Content;

And use Json.Net to deserialize your json string :

JObject jsonResponse = (JObject)JsonConvert.DeserializeObject(response.Content);
var messageList = JsonConvert.DeserializeObject<List<Message>>(jsonResponse["messages"].ToString()‌​);
Sign up to request clarification or add additional context in comments.

5 Comments

I tried this out, and responseContent is a string that looks like {"key1": "value1", "key2": "value2" ...}. When the program hits the DeserializeObject line, I get a JsonSerializationException: "Cannot deserialize the current JSON object into type because the type requires a JSON array to deserialize correctly." I've tried a few things I've found online to convert a JSON string to array, but keep running into errors. Does there need to be a property in the message class for every key in the JSON to deserialize correctly?
can you post the json?
I figured it out - the json response had a lot of properties, and one of those was the list of messages. So when I tried to deserialize the entire response into a list of Message objects, it gave an error, since it wasn't a JSON response of messages.
This is the code that worked: var response = client.Execute(request); JObject jsonResponse = (JObject)JsonConvert.DeserializeObject(response.Content); var messageList = JsonConvert.DeserializeObject<List<Message>>(jsonResponse["messages"].ToString());
@jmk22 ok because the body content is wrapped into the response.... I'll edited the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.