如何将JSON返回反序列化为从RestSharp调用到API的对象数组?

时间:2016-04-07 00:46:53

标签: c# json restsharp json-deserialization

我正在尝试将从RestSharp调用的JSON返回反序列化为API。

这是一个C#控制台应用程序。到目前为止,这是我的代码:

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

响应是一个JSON格式的邮件列表,其中的密钥包括"to""from""body""status"。这有点像:

{
  "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"
},

我希望将其转换为Message个对象的数组,其中Message类看起来像这样:

class Message
{
    public string To { get; set; }
    public string From { get; set; }
    public string Body { get; set; }
    public string Status { get; set; }
}

我一直在寻找如何将JSON转换为对象并找到此页面:http://blog.atavisticsoftware.com/2014/02/using-restsharp-to-deserialize-json.html。页面上的第三个例子与我想要的一致。

我对程序进行了一些更改,现在它看起来像这样:

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

但是,运行程序时messageList为空。将JSON响应转换为对象列表,我错过了什么? RestSharp Documentation使它看起来相当简单。

1 个答案:

答案 0 :(得分:3)

我对RestSharp了解不多,但你可以得到这样的响应内容字符串:

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

并使用Json.Net反序列化您的json字符串:

JObject jsonResponse = (JObject)JsonConvert.DeserializeObject(response.Content);
var messageList = JsonConvert.DeserializeObject<List<Message>>(jsonResponse["messages"].ToString()‌​);