2012-08-31 29 views
1

我有了這個JSON數據的URL:如何從一個JSON請求,並顯示在metro應用獲取數據

[{"title":"Snow White & the Huntsman","year":2012,"released":1338534000,"url":"http://localhost/movie/snow-white-and-the-huntsman-2012","trailer":"http://youtube.com/watch?v=11Wn-_uyT48","runtime":127,"tagline":"","overview":"After the Evil Queen marries the King, she performs a violent coup in which the King is murdered and his daughter, Snow White, is taken captive. Almost a decade later, a grown Snow White is still in the clutches of the Queen. In order to obtain immortality, The Evil Queen needs the heart of Snow White. After Snow escapes the castle, the Queen sends the Huntsman to find her in the Dark Forest.","certification":"PG-13","imdb_id":"tt1735898","tmdb_id":"58595","poster":"http://trakt.us/images/posters_movies/180748.1.jpg","images":{"poster":"http://trakt.us/images/posters_movies/180748.1.jpg","fanart":"http://trakt.us/images/fanart_movies/180748.1.jpg"},"watchers":15,"ratings":{"percentage":68,"votes":105,"loved":71,"hated":34},"genres":["Adventure","Fantasy","Action","Drama"]} 

我試圖解析這一點,在我的metro應用顯示,但我不能讓它爲我的生活興田工作!我已經嘗試了很多東西,例如:

 string trendingURL = "http://Localhost/movies/trending.json/"; 


     MovieDetails newMovie = new MovieDetails(); 
     newMovie.title = ""; 
     newMovie.cover = ""; 

     //DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MovieDetails)); 

     //StreamReader sr = new Stream(trendingURL); 

     HttpClient client = new HttpClient(); 

     HttpResponseMessage response = await client.GetAsync(trendingURL); 
     var str = await response.Content.ReadAsStreamAsync(); 
     var ser = new DataContractJsonSerializer(typeof(MovieDetails)); 
     var collection = (MovieDetails)ser.ReadObject(str); 
     var results = collection.title; 

回答

0

使用Json.Net

using (var wc = new WebClient()) 
{ 
    string json = await wc.DownloadStringTaskAsync(trendingURL); 
    dynamic obj = JsonConvert.DeserializeObject(json); 
    foreach (var item in obj) 
    { 
     Console.WriteLine("{0} - {1} - {2} - {3}", 
        item.title, 
        item.year, 
        item.images.poster, 
        item.ratings.votes); 
    } 
} 
+0

我喜歡這種方法,但由於這些都是動態的,我怎麼會檢索此類信息使用? – KPS

+0

沒關係,我覺得愚蠢:) – KPS

0

你試過Json.NET庫嗎?據Codeplex上,它支持Windows 8,所以你可以做這樣的事情:

var o = JObject.Parse(YOUR_JSON_STRING); 
var newMovie = new MovieDetails(); 
newMovie.title = (string)o["title"]; 
newMovie.cover = (string)o["cover"]; 
+0

-1'JObject.Parse'會拋出異常,因爲它是'JArray' –

0

使用非法經營:

var client = new HttpClient("http://Localhost/"); 
var details = client.Get("movies/trending.json").OnOk().As<MovieDetails>(); 

可以使用的NuGet安裝非法經營。

+0

看起來這不適用於.NET 4.5,它很快就會支持它? – KPS

+0

它沒有支持.NET 4.5,你可以使用.NET 4.0組件與.NET 4.5的。 – jonnii