ASP.NET MVC 5从TMDB API获取JSON结果

时间:2015-05-13 08:15:59

标签: c# json asp.net-mvc-5 themoviedb-api

如何让用户在ASP.NET MVC 5应用程序中使用TMDB API(The Movie Db)搜索电影并返回JSON结果。

使用我的personel api键在VB外部运行示例并返回包含字符串“mission”的所有电影的json结果:

// map::lower_bound/upper_bound
#include <iostream>
#include <map>

int main ()
{
  std::map<char,int> mymap;
  std::map<char,int>::iterator itlow,itup;

  mymap['a']=20;
  mymap['b']=40;
  mymap['c']=60;
  mymap['d']=80;
  mymap['e']=100;

  itlow=mymap.lower_bound ('b');  // itlow points to b
  itup=mymap.upper_bound ('d');   // itup points to e (not d!)

  mymap.erase(itlow,itup);        // erases [itlow,itup)

  // print content:
  for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';

  return 0;
}

文档(http://docs.themoviedb.apiary.io/#reference/search/searchmovie)建议在C#中使用以下代码:

http://api.themoviedb.org/3/search/movie?api_key=841c..&query=mission

我将代码粘贴到异步操作MovieSearch()中,但不知道现在要做什么。

2 个答案:

答案 0 :(得分:2)

您必须将他们返回的JSON字符串反序列化为responseData为c#类型,如Movie。对于反序列化,您可以使用像JSON.NET这样的库,然后写这样的:

class Movie
{
   public string Name{ get; set;}
   public decimal Rating{ get; set;}
}

 string output = "{ "Name": "The Matrix", "Rating": "4.0"}"

Movie deserializedMovie = JsonConvert.DeserializeObject<Movie>(responseData);

检查它们实际返回的是什么,因为响应不能包含单个Movie对象但可以包含List,那么你必须像这样编写代码:

List<Movie> movies= JsonConvert.DeserializeObject<List<Movie>>(responseData);

希望这会有所帮助:)

答案 1 :(得分:1)

感谢Aminuls提供了有用的答案,我找到了一个很好的解决方案:

// SearchMovie method

public async Task MovieSearch(string search)
{          
    System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

    var baseAddress = new Uri("http://api.themoviedb.org/3/");

    using (var httpClient = new HttpClient { BaseAddress = baseAddress })
    {     
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");

        // api_key can be requestred on TMDB website
        using (var response = await httpClient.GetAsync("search/movie?api_key=941c...&query=" + search))
        {
            string responseData = await response.Content.ReadAsStringAsync();

            var model = JsonConvert.DeserializeObject<RootObject>(responseData);

            foreach (var result in model.results)
            {
                // All movies
                // System.Diagnostics.Debug.WriteLine(result.title);
            }      
        }
    }
}

// Generated model from json2csharp.com

public class Result
{
    public bool adult { get; set; }
    public string backdrop_path { get; set; }
    public int id { get; set; }
    public string original_title { get; set; }
    public string release_date { get; set; }
    public string poster_path { get; set; }
    public double popularity { get; set; }
    public string title { get; set; }
    public bool video { get; set; }
    public double vote_average { get; set; }
    public int vote_count { get; set; }
}

public class RootObject
{
    public int page { get; set; }
    public List<Result> results { get; set; }
    public int total_pages { get; set; }
    public int total_results { get; set; }
}

// Examle of search functionaly in View

@Html.ActionLink("Search movie", "MovieSearch", new { search = "mission"})