Данные не десериализуются в List‹SearchResults›

Я использую RestSharp для извлечения некоторых данных из Cambridge Dictionaries 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
}

person Joel Dean    schedule 11.10.2012    source источник
comment
Вы не должны включать ключ API, который все еще действителен. [причина безопасности]   -  person Benjamin    schedule 28.10.2012
comment
Я не совсем понимаю, что вы имеете в виду, не могли бы вы немного пояснить?   -  person Joel Dean    schedule 29.10.2012
comment
Вы вставили ключ API, чтобы все могли его использовать. надо было стереть :)   -  person Benjamin    schedule 29.10.2012


Ответы (1)


Что-то вроде этого должно помочь:

public class SearchResultResponse
{
    public int ResultsNumber { get; set; }
    public IEnumerable<SearchResult> Results { get; set; }
}

public class SearchResult
{

    public string entryLabel { get; set; }
    public string entryUrl { get; set; }
    public string entryId { get; set; }
}

SearchResultResponse obj = JsonConvert.DeserializeObject<SearchResultResponse>(json);

В вашем случае вам, возможно, придется вызвать client.ExecuteAsync следующим образом:

client.ExecuteAsync<SearchResultResponse>
person nick_w    schedule 11.10.2012