我正在使用 RestSharp 从剑桥词典 API中检索一些数据,用于一个简单的 Windows Phone 7 应用程序。当我执行搜索查询时,我会以 JSON 格式获得结果,因为我检查了response.Content并且实际上返回了结果,但是当我尝试反序列化结果并将其绑定到列表框元素时,它将不起作用。这是代码:
请求处理程序类
namespace RestAPI
{
/// <summary>
/// This class is responsible for communicating with a RESTful web service.
/// </summary>
public class RequestHandler
{
//this property stores the API key
readonly string Accesskey = "";
//this property stores the base URL
readonly string BaseUrl = "https://dictionary.cambridge.org/api/v1/dictionaries/british/search";
//readonly string BaseUrl = "https://dictionary.cambridge.org/api/v1/dictionaries";
//Instance of the RestClient
private RestClient client;
//Constructor that will set the apikey
public RequestHandler(string Access="Doh52CF9dR8oGOlJaTaJFqa05PysEKIbEvd9VNQ7CqB81MyTUCggGNQO7PDyrsyY")
{
this.Accesskey = Access.Trim();
client = new RestClient(this.BaseUrl);
}
//Execute function
public List<SearchResult> Execute(string word)
{
List<SearchResult> data = new List<SearchResult>();
RestRequest request = new RestRequest();
request.RequestFormat = DataFormat.Json;
request.AddHeader("accessKey",Accesskey);
request.AddParameter("pageIndex","1");
request.AddParameter("pageSize","5");
request.AddParameter("q",word.Trim());
client.ExecuteAsync<List<SearchResult>>(request,(response)=>{
try
{
var resource = response.Data;
if(response.ResponseStatus == ResponseStatus.Completed)
MessageBox.Show(resource.Count.ToString());
//MessageBox.Show(resource.ToString());
foreach(SearchResult s in resource)
{
data.Add(s);
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
});
return data;
}
}
}
主页文件后面的代码。
namespace RestAPI
{
public partial class MainPage : PhoneApplicationPage
{
public RequestHandler handler = new RequestHandler();
public List<SearchResult> info = new List<SearchResult>();
// Constructor
public MainPage()
{
InitializeComponent();
}
private void search_Click(object sender, RoutedEventArgs e)
{
info = handler.Execute(searchBox.Text);
listBox1.Items.Add("Testing");
foreach (SearchResult s in info)
{
listBox1.Items.Add(s.entryLabel);
}
}
}
}
数据被反序列化到的模型类。
namespace RestAPI
{
public class SearchResult
{
public string entryLabel{get;set;}
public string entryUrl{get;set;}
public string entryId { get; set; }
}
}
返回的示例 JSON 数据。
{
"resultNumber": 49,
"results": [
{
"entryLabel": "dog noun ANIMAL ",
"entryUrl": "http://dictionary.cambridge.org/dictionary/british/dog_1",
"entryId": "dog_1"
},
{
"entryLabel": "dog noun PERSON ",
"entryUrl": "http://dictionary.cambridge.org/dictionary/british/dog_2",
"entryId": "dog_2"
},
{
"entryLabel": "dog verb FOLLOW ",
"entryUrl": "http://dictionary.cambridge.org/dictionary/british/dog_3",
"entryId": "dog_3"
}
],
"dictionaryCode": "british",
"currentPageIndex": 1,
"pageNumber": 17
}