2015-07-05 60 views
-1

的模型,我有以下的ActionResult:MVC 5填充的Json

public ActionResult WeatherWidget() 
{ 
    string json = string.Empty; 
    using (var client = new WebClient()) 
    { 
     json = client.DownloadString("http://api.wunderground.com/api/xxxxxxxxx/geolookup/conditions/forecast/q/Australia/sydney.json"); 
    } 

    WeatherWidget weatherWidget = new WeatherWidget() 
    { 
     //What do I put in here? 
    }; 

    return View(weatherWidget); 
} 

及以下型號:

public class WeatherWidget 
{ 
    public string city { get; set; } 
    public string lat { get; set; } 
    public string lon { get; set; } 
} 

這裏是JSON的一個片段:

{ 
    "response": { 
    "version":"0.1", 
    "termsofService":"http://www.wunderground.com/weather/api/d/terms.html", 
    "features": { 
    "geolookup": 1 
    , 
    "conditions": 1 
    , 
    "forecast": 1 
    } 
    } 
    ,"location": { 
     "type":"INTLCITY", 
     "country":"AU", 
     "country_iso3166":"AU", 
     "country_name":"Australia", 
     "state":"VC", 
     "city":"Falls Creek", 
     "tz_short":"AEST", 
     "tz_long":"Australia/Melbourne", 
     "lat":"-36.86999893", 
     "lon":"147.27000427", 
     "zip":"00000", 

如何填充模型以顯示在我的視圖中?

如:@ Model.city@ Html.Raw(Model.city)

我在視圖中顯示通過Javascript的數據沒有問題,我可以用XML和HTML使用做到這一點HtmlAgilityPack,我只是不能解決如何與Json做到這一點。

+0

使用Newtonsoft.Json並使用適當的屬性創建一系列POCO對象。 – krillgar

+0

你有沒有例子? – Bojangles

回答

1

通過的NuGet添加Newtonsoft.Json,添加以下using語句

using Newtonsoft.Json; 
using Newtonsoft.Json.Linq; 

,然後使用下面的代碼來提取數據從你的JSON響應。

JObject parsedJson = (JObject)JsonConvert.DeserializeObject(json); 
    JObject location = (JObject)parsedJson["location"]; 
    WeatherWidget weatherWidget = new WeatherWidget(); 
    weatherWidget.city = location["city"]; 
    weatherWidget.lat = location["lat"]; 
    weatherWidget.lon = location["lon"];